【问题标题】:reverse() function in Django class based views with argument带参数的基于 Django 类的视图中的 reverse() 函数
【发布时间】:2026-02-05 19:50:02
【问题描述】:

我有一个这样的网址:

url(r'^(?P<user_id>\d+)/profile/$', views.ProfileView.as_view(), name='profile'),

当用户点击Update Profile 时,我会更新表单并使用messaging framework 重定向到与message 相同的配置文件URL。

# views

# Use the message framework to pass the message profile successfully updated
messages.success(request, 'Profile details updated.')

# Redirect to the same view with the profile updated successfully message
return HttpResponseRedirect(reverse('profile', args=(request.user.id,)))

但我收到此错误:

NoReverseMatch at /5/profile/

Reverse for 'profile' with arguments '(5L,)' and keyword arguments '{}' not found.

怎么了?

【问题讨论】:

    标签: django django-views django-urls


    【解决方案1】:

    由于 Python 2.x.x 的工作原理,您会得到它。

    来自数据库行的所有整数都将以Ll 为后缀(通常为大写L)。

    一种快速而肮脏的方法是

    return HttpResponseRedirect(reverse('profile', args=(int(long(request.user.id)),)))
    

    【讨论】:

      最近更新 更多