Django:用户配置文件的动态URL

时间:2017-11-06 05:37:56

标签: django url django-urls

所以我试图为我的用户制作一个非常传统的动态网址个人资料页面。所以,例如。 www.website.com/profile/(username)

当我输入有效的用户名时,我收到NoReverseMatch的错误,我不知道为什么。以下是我的代码片段

urls.py

urlpatterns = [
url(r'^admin/', admin.site.urls),

url(r'^signup/$', accountsViews.signup, name="signup"),
url(r'^logout/$', authViews.LogoutView.as_view(), name='logout'),
url(r'^login/$', authViews.LoginView.as_view(template_name='login.html'), name="login"),
url(r'^find/$', findViews.find, name="find"),
# url(r'^profile/$', accountsViews.profile, name="profile"),
url(r'profile/(?P<username>.+)/$', accountsViews.profile, name="profile"),
url(r'^$', views.home, name="home"),]

views.py

def profile(request, username=None):
if User.objects.get(username=username):
    user = User.objects.get(username=username)
    return render(request, "profile.html", {
        "user": user,
    })
else:
    return render("User not found")

html文件

{% if user.is_authenticated %}
                {% url 'profile' as profile_url %}
                <li {% if request.get_full_path == profile_url %}class="active"{% endif %}><a href="{% url 'profile' %}"><span class="glyphicon glyphicon-user"></span> Profile </a></li>
                <li><a href="{% url 'logout' %}"><span class="glyphicon glyphicon-log-out"></span> Log Out</a></li>
            {% endif %}

此外,如果有帮助,错误消息会突出显示&#34; {%url&#39;个人资料&#39; %}&#34;部分作为错误,并声称它没有反向匹配。但是,在我的urls.py中,你可以清楚地看到我做了名字=&#34; profile&#34;

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:4)

您应该将用户名放在个人资料

的网址模板标签中
{% url 'profile' user.username %}
  

检查文档:   https://docs.djangoproject.com/en/1.11/topics/http/urls/#examples