0

我有一个使用身份验证的 django 应用程序,用户可以在其中查看彼此的个人资料。

在我看来.py

def display(request, edit=False, pk=None): 
    if not pk:
        pk = request.user.profile.pk

    profile = Profile.objects.get(pk=pk)
    d = get_user_info(profile) # returns a dictionary of some info from a user's profile

    if edit and request.user == profile.user:
        return render(request, 'edit_profile.html', d)
    else:
        return render(request, 'profile.html', d)

在我的模板中,我想为用户提供单击链接的选项,如果他们正在查看自己的个人资料,则允许他们编辑信息。

{% if request.user == profile.user %}
    <a href="{% url "edit_profile" %}">edit</a>
{% endif %}

我对此有两个问题。
首先:我认为使用 render() 可以让我访问request模板内部。但是,这是行不通的。我做错了吗?还是我需要明确地通过render字典?

d['request']=request    
return render(request, 'profile.html', d) 

第二:这样可以吗?还是我应该以其他方式这样做?

4

1 回答 1

3

Django 有一个请求上下文处理器request,可以在模板上下文中添加对象。默认情况下不会添加此功能,因此您需要在TEMPLATE_CONTEXT_PROCESSORS设置中启用它。

但是,django 将 current 添加request.useruser上下文变量,因此如果足够的话,您可以使用它。

于 2013-09-06T03:39:44.067 回答