【问题标题】:Django: dynamic URL for user profilesDjango:用户配置文件的动态 URL
【发布时间】:2018-04-18 05:29:47
【问题描述】:

所以我正在尝试为我的用户制作一个非常传统的动态 URL 配置文件页面。所以例如。 www.website.com/profile/(用户名)

当我输入有效的用户名时,我收到 NoReverseMatch 错误,我不知道为什么。这是我的代码的sn-ps

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 %}

如果有帮助,错误消息会突出显示“{% url 'profile' %}”部分作为错误,并声称它没有反向匹配。但是,在我的 urls.py 中,你可以清楚地看到我已经完成了 name="profile"

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 视图中的if 声明毫无意义。 get() 要么返回值,要么引发异常。

标签: django url django-urls


【解决方案1】:

你应该把用户名放在个人资料的url模板标签中

{% url 'profile' user.username %}

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

【讨论】:

  • 谢谢,这似乎解决了问题。不过,可以。请你帮我完全理解吗?即使我以 A 身份登录,我也希望能够访问 Bs 的个人资料。在当前的实施中,它不会只显示当前登录的用户的个人资料吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
  • 2011-08-05
  • 1970-01-01
相关资源
最近更新 更多