【问题标题】:Display username in URL - Django在 URL 中显示用户名 - Django
【发布时间】:2015-02-18 21:43:16
【问题描述】:

当我尝试在 URL 中显示用户名时,我收到以下错误:

未找到带有参数“()”和关键字参数“{}”的“account_home”的反向操作。尝试了 1 种模式:['/(?P\w+)/$']。

这是我的意见.py

@login_required
def account_home(request, username):
    u = MyUser.objects.get(username=username)
    return render(request, "accounts/account_home.html", {})

这是我的 urls.py

urlpatterns += patterns('accounts.views',
    # url(r'^account/$', 'account_home', name='account_home'),
    url(r'^/(?P<username>\w+)/$', 'account_home', name='account_home'),
    url(r'^logout/$', 'auth_logout', name='logout'),
    url(r'^login/$', 'auth_login', name='login'),
    url(r'^register/$', 'auth_register', name='register'),
)

这是它试图渲染的代码,但不能。

提前感谢您的帮助!

【问题讨论】:

    标签: python django url django-views


    【解决方案1】:

    简答:问题出在您的模板代码上。您没有将 username 参数传递给您的视图。而不是

    <a href="{% url 'account_home' %}">Account<a>
    

    试试

    <a href="{% url 'account_home' user.username %}">Account<a>
    

    长答案:话虽如此,您可能可以通过修改视图来摆脱username 参数。您已经在视图中的 request 对象中拥有当前用户:

    @login_required
    def account_home(request):
        u = MyUser.objects.get(username=request.user.username)
        return render(request, "accounts/account_home.html", {})
    

    并将其从 url 定义中删除:

    url(r'^$', 'account_home', name='account_home'),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 2021-11-18
      • 2013-06-05
      相关资源
      最近更新 更多