【问题标题】:NoReverseMatch at Reverse for ... with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []NoReverseMatch at Reverse for ... 未找到参数“()”和关键字参数“{}”。尝试了 0 种模式:[]
【发布时间】:2016-03-18 18:58:40
【问题描述】:

我正在尝试了解为什么在使用我创建的用户注册表单时收到 NoReverseMatch 错误:

根据我的情况,参考相关文件/资料:

我有一个名为 neurorehab/urls.py 的主 urls.py 文件

from django.conf.urls import include, url, patterns
from django.conf import settings
from django.contrib import admin
from .views import home, home_files

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', home, name='home'),

    url(r'^', include('userprofiles.urls')),
    #Call the userprofiles/urls.py

    url(r'^(?P<filename>(robots.txt)|(humans.txt))$', home_files, name='home-files'),


]

# Response the media files only in development environment
if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT,}),
)

我有名为 userprofiles 的模块/应用程序,其中有这样的 userprofiles/urls.py 文件:

from django.conf.urls import include, url, patterns
from .views import (ProfileView, LogoutView,
                AccountRegistrationView, PasswordRecoveryView,
                SettingsView)
from userprofiles.forms import CustomAuthenticationForm

urlpatterns = [
    url(r'^accounts/profile/$', ProfileView.as_view(), name='profile/'),

    # Url that I am using for this case
    url(r'^register/$', AccountRegistrationView.as_view(), name='register'),

    url(r'^login/$','django.contrib.auth.views.login', {
                    'authentication_form': CustomAuthenticationForm,
                    }, name='login',
),
    url(r'^logout/$', LogoutView.as_view(), name='logout'),
]

url register 调用位于 userprofiles/urls.py 中的 CBV AccountRegistrationView 是这样的:

from django.shortcuts import render
from django.contrib.auth import login, logout, get_user, authenticate
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader

# Importing classes for LoginView form
from django.views.generic import FormView, TemplateView, RedirectView
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse, reverse_lazy

from .mixins import LoginRequiredMixin
from .forms import  UserCreateForm

class AccountRegistrationView(FormView):
    template_name = 'signup.html'
    form_class = UserCreateForm

    # Is here in the success_url in where I use reverse_lazy and I get
    # the NoReverseMatch
    success_url = reverse_lazy('accounts/profile')
    #success_url = '/accounts/profile'

    # Override the form_valid method
    def form_valid(self, form):
        # get our saved user with form.save()
        saved_user = form.save()
        user = authenticate(username = saved_user.username,
                            password = form.cleaned_data['password1'])

        # Login the user, then we authenticate it
        login(self.request,user)

        # redirect the user to the url home or profile
        # Is here in the self.get_success_url in where I  get
        # the NoReverseMatch
        return HttpResponseRedirect(self.get_success_url())

我在其中制作注册表单的表单类 UserCreateForm 位于 userprofiles/forms.py 文件中,它是这样的:

from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

class UserCreateForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserCreateForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.add_input(Submit('submit', u'Save'))

    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username','email','password1','password2',)

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data['email']

        if commit:
            user.save()
        return user

我的模板是 userprofiles/templates/signup.html 文件:

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Register{% endblock %}
{% block content %}

<div>
    {% crispy form %}
    {% csrf_token %}

</div>
{% endblock %}

当我转到我的注册用户表单时,我按下提交保存我的用户,我有它尝试重定向到最近创建的用户的个人资料,但我收到此错误

在这种情况下,我可能会发生什么。好像reverse_lazy不起作用?

任何帮助将不胜感激:)

【问题讨论】:

    标签: python django django-class-based-views http-redirect


    【解决方案1】:

    reverse_lazy() 函数采用视图函数或 url 名称来解析它,而不是 url 路径。所以你需要把它称为

    success_url = reverse_lazy('profile/')
    #---------------------------^ use url name
    

    但是,我不确定'/' 字符是否适用于网址名称。

    如果你必须使用路径来解析一个url,使用resolve()函数。

    【讨论】:

    • 谢谢,事实上,userprofiles/urls.py 中的 'accounts/profile' url 中的属性名称中的字符 '/' 我已经删除它并且可以使用。 :D
    猜你喜欢
    • 2015-10-15
    • 2020-10-21
    • 2018-03-28
    • 2016-01-31
    • 2020-07-20
    • 2019-04-17
    • 2018-11-25
    • 2019-11-01
    • 1970-01-01
    相关资源
    最近更新 更多