反向的NoReverseMatch for ...找不到参数'()'和关键字参数'{}'。尝试过0种模式:[]

时间:2015-12-13 03:28:15

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

我正在尝试理解为什么在使用我创建的用户注册表单时出现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'),
]

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

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

enter image description here

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

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:1)

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

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

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

如果必须使用路径解析为网址,请使用resolve()功能。