django.urls.exceptions.NoReverseMatch:找不到“登录”的反向。 “登录”不是有效的视图函数或模式名称

问题描述 投票:0回答:1

我收到错误:

 django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name.
在 URL 中写入
https://chalets.com:8000/accounts/login
时。我注意到,当从 urls.py 中删除帐户的命名空间和 app_name 时,URL 会反转以成功登录。我想知道为什么使用命名空间时会出现错误? 以及如何解决该错误?

这是 urls.py:

from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('accounts/', include('accounts.urls', namespace='accounts')),
    path('social-auth/', include('social_django.urls', namespace='social')),
    path('', include('homepage.urls', namespace='home')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
 

以及账户的urls.py:

from django.urls import path
from accounts.views import SignUpView, LogoutView, LoginView

app_name = 'accounts'

urlpatterns = [
    path('signup', SignUpView.as_view(), name='signup'),
    path('login', LoginView.as_view(), name='login'),
    path('logout', LogoutView.as_view(), name='logout')
]


views.py:

class SignUpView(generic.CreateView):
    form_class    = SignUpForm
    template_name = 'signup.html' 
    
    def form_valid(self, form):
        # get data from form
        email     = form.cleaned_data['email']
        password1 = form.cleaned_data['password1']
        password2 = form.cleaned_data['password2']
        # save user in database with hash password
        user      = User(email=email, password=password1)
        user.set_password(password1)
        user      = user.save()
        # authenticate, login, and redirect to home
        user      = authenticate(email=email, password=password1)
        login(self.request, user)
        return redirect('home')



class LoginView(generic.FormView):
    template_name = 'login.html'
    form_class    =  LoginForm 

    def form_valid(self, form):
        # get data from for and authenticate
        email    = form.cleaned_data['email']
        password = form.cleaned_data['password']
        user     = authenticate(email=email, password=password)
        
        if user is not None:
            login(self.request, user)
            return redirect('home')
        else:
            messages.info(self.request, 'invalid username or password')
            return redirect('accounts:login')



class LogoutView(views.LogoutView):
    next_page = '/'
django django-urls
1个回答
0
投票

如果您添加命名空间,

app_name = 'accounts'
,那么您需要修改视图和模板以包含该命名空间。

# Example usage in the view
return redirect('accounts:login')

然后在模板中你可以做这样的事情:

<a href="{% url 'accounts:login' %}">

重点是,如果您有两个不同的应用程序并且想要在每个应用程序中使用相同的视图名称。

© www.soinside.com 2019 - 2024. All rights reserved.