我尝试在PK上显示用户个人资料。所以,我创建了一个名为“Profile”的菜单。用户单击菜单后,用户可以看到该配置文件。
我试过了:
def view_profile(request, pk):
profile = get_object_or_404(User, pk=pk)
return render(request, 'girl/base.html', {'profile':profile})
还有这个:
def view_profile(request, pk):
profile = User.objects.filter(User, pk=pk)
return render(request, 'base.html', {'profile':profile})
在base.html中:
{% if user.is_authenticated %}
<a href='{% url "profile" pk=profile.pk%}' class="prof"><span class="pro">Profile</span></a>
{% endif %}
在模板中,profile.html:
{% extends 'base.html' %}
{% block content %}
{% if user.is_authenticated %}
<h2><a href="{% url 'profile' pk=profile.pk %}">{{ profile.username }}</a></h2>
{% endif %}
{% endblock %}
urls.py
url(r'^cat/(?P<pk>\d+)/profile/$', views.view_profile, name='profile')
配置文件从未显示,我收到以下错误:
Reverse for 'profile' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['cat/(?P<pk>\\d+)/profile/$']
答案 0 :(得分:0)
你的问题很难理解,所以我在猜测。
只有在个人资料视图本身的上下文中才会出现名为“个人资料”的内容。但您的基本模板用于所有视图,而所有其他视图不具有该变量可用;所以它不能使用该值来创建个人资料链接。
但是我不知道为什么你认为你需要这个变量。你想要的不是简介,而是当前的用户;通过名为unsurprisingly user
的变量,它总是在模板中可用 - 如您所知,因为您已经使用它来检查身份验证状态。您应该在基本模板中使用它:
{% if user.is_authenticated %}
<a href='{% url "profile" pk=user.pk%}' class="prof"><span class="pro">Profile</span></a>
{% endif %}
另请注意,您的第二版Profile视图本身是错误的。