Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 比较django中的url_Python_Html_Django - Fatal编程技术网

Python 比较django中的url

Python 比较django中的url,python,html,django,Python,Html,Django,我试图在用户访问自己的个人资料时隐藏内容。我尝试了下面的代码,但没有成功。可能有什么问题 {% if request.path == "/account/users/{{ request.user.username }}/" %} {% else %} <img src="https://tyllplus.com/static/arrow-orange-down-vector-1.png" width="30" height="30"> {% endif %} {%if

我试图在用户访问自己的个人资料时隐藏内容。我尝试了下面的代码,但没有成功。可能有什么问题

 {% if request.path == "/account/users/{{ request.user.username }}/" %}

  {% else %}

<img src="https://tyllplus.com/static/arrow-orange-down-vector-1.png" width="30" height="30">
{% endif %}
{%if request.path==”/account/users/{{request.user.username}}/“%}
{%else%}
{%endif%}
(高级)字符串处理不应在模板中完成。尤其是不使用URL,因为以后可能需要更改视图。即使您设法让它工作,如果您以后有一个前缀路径,它也可能开始失败。此方法还严重依赖于URL的格式:如果以后指定使用
id
而不是
username
的URL,则需要查找依赖于此格式的所有URL处理。这不是优雅的设计

当然,简单的处理是没有问题的。例如,向数字添加逗号分隔符等通常由模板标记处理。但在我看来,URL并不真正属于这一类

您最好在视图中对该逻辑进行编码(或者确保可以通过视图中的元素轻松地检测到它)

例如,对于
详细视图

from django.views.generic.detail import DetailView

from django.contrib.auth.models import User

class UserDetailView(DetailView):
    model = User
    context_object_name = 'my_user'
    template = 'user_detail.html'
我们知道
my_user
变量将携带
user
对象ot显示,因此我们可以通过以下方式进行验证:

{% if my_user != request.user %}
<!-- show something -->
{% else %}
<!-- show something else -->
{% endif %}
{%if my_user!=request.user%}
{%else%}

{%endif%}
如果这是一个配置文件详细视图,那么您肯定有配置文件对象的
用户
作为上下文变量随时可用。虽然您可以在模板中这样做,但它不属于模板,您最好将其添加到视图中。@Willem我想知道如何通过这种方式实现它。你能再详细一点吗?@kingiyk:答案中已经有了。您将以某种方式传递所呈现的
用户
(或者您应该传递),例如,通过在上下文数据中传递一个名为
my_user
的变量,然后在template.thnx中检查它以获取帮助。我用{%if request.user.username in request.path%}解决了这个问题,以防任何人需要它。