如何在Django中修复NoReverseMatch?

时间:2019-10-29 15:54:22

标签: django

这是详细信息错误:     在/ accounts / login /

处进行NoReverseMatch
Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['users/(?P<username>
[^/]+)/$']

Request Method:     POST
Request URL:    http://192.168.109.138:8000/accounts/login/
Django Version:     2.1.7
Exception Type:     NoReverseMatch
Exception Value:    

Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['users/(?P<username>
[^/]+)/$']

用户应用中的views.py部分:

class UserUpdateView(LoginRequiredMixin, UpdateView):

model = User
fields = ["nickname", "job_title", "introduction", "picture", "location", "personal_url",
          "weibo", "zhihu", "github", "linkedin"]
template_name = "users/user_form.html"

def get_success_url(self):
    return reverse("users:detail", kwargs={"username": self.request.user.username})

def get_object(self, queryset=None):
    return self.request.user

我不知道reverse()函数如何工作以及args和kwargs的用途是什么

users \ urls.py:

from django.urls import path
from zhuri02.users import views


app_name = "users"
urlpatterns = [
path("update/", views.UserUpdateView.as_view(), name="update"),
path("<username>/", views.UserDetailView.as_view(), name="detail"),
]

config \ urls.py

urlpatterns = [
    path("users/", include("zhuri02.users.urls", namespace="users")),
    path("accounts/", include("allauth.urls")),
# Your stuff: custom urls includes go here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我不确定如何解决此错误,请提供帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

尝试替换您的`urls.py,所以不要这样做:

{
   "0" : 'foo',
   "1" : 'bar'
}

你有这个。注意类型path("<username>/", views.UserDetailView.as_view(), name="detail"),

slug

您可以使用path('<slug:username>/', views.UserDetailView.as_view(), name='detail'), 代替一些东西,例如slugstr等。

此处更多信息https://docs.djangoproject.com/en/2.2/topics/http/urls/#path-converters