首页 > 解决方案 > Django - 注销视图自定义失败

问题描述

虽然最初的问题已被清除,但有一个新的相关问题非常有趣:(请让我知道我的理论是否正确......)

请在下面查看我的 urlpatterns:

from django.contrib.auth import views as auth_views
from boutique.models import Category
from django.urls import path, include
from . import views

app_name = 'users'
urlpatterns = [

    # to customise login view
    path('login/', auth_views.LoginView.as_view(extra_context = {'categories': Category.objects.get_categories_with_item()})),
    # path('login/', views.NewLoginView.as_view()),

    # to customise default logout view
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.get_categories_with_item()}),

    # include django authentication urls
    path('', include('django.contrib.auth.urls')),

可能你已经注意到了有两种不同的传入方式extra_context,有趣的是:使用的方法LogoutView不能使用on LoginView!!但是,使用的方法LoginView确实适用于LogoutView.

我认为可能的解释是他们继承了不同的观点,但尚未得到你们的证实:

LoginView

class LoginView(SuccessURLAllowedHostsMixin, FormView):
    """
    Display the login form and handle the login action.
    """
    form_class = AuthenticationForm
    authentication_form = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/login.html'
    redirect_authenticated_user = False
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            self.redirect_field_name: self.get_redirect_url(),
            'site': current_site,
            'site_name': current_site.name,
            **(self.extra_context or {})
        })
        return context

LogoutView

class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
    """
    Log out the user and display the 'You are logged out' message.
    """
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/logged_out.html'
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            'site': current_site,
            'site_name': current_site.name,
            'title': _('Logged out'),
            **(self.extra_context or {})
        })
        return context

我认为LoginView必须将extra_context作为位置参数传递给的原因.as_view()是它不继承自TemplateView

class TemplateView(TemplateResponseMixin, ContextMixin, View):
    """
    Render a template. Pass keyword arguments from the URLconf to the context.
    """
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

它有一种get获取上下文数据的方法......如果我没记错的话。

谁能证实这一点?

我对 python 和 django 框架很陌生。非常感谢!!!


原问题已回答

请在评论环节查看答案——


我对 Django 相当陌生,为了将更多上下文传递给注销视图,我尝试了 2 种方法来自定义注销视图:

方法一:

from django.contrib.auth import views as auth_views
from boutique.models import Category

app_name = 'users'
urlpatterns = [
    ...
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),

    # I also tried this:
    # path('logout/', auth_views.LogoutView.as_view({'categories': Category.objects.all()}),


    # I also tried this: 
    # path('logout-customised-url/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),
    # This is working tho it wouldn't be automatically redirect to this path when logged out

方法二:

    ...
    path('logout/', views.NewLogoutView.as_view()),
    # NewLogoutView code below:

视图.py

from boutique.models import Category
from django.contrib.auth.views import LogoutView


class NewLogoutView(LogoutView):

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context

仍然无法正常工作,结果完全相同:如果正在使用自定义 url,例如“logged-out/”而不是“logout/”,并且您输入了 url,它会呈现带有额外上下文的正确页面. 但是,当用户正常注销时不会转到该页面...

有什么解决方法吗?谢谢!

标签: pythondjangourlviewlogout

解决方案


您需要传入extra_context您的urls.py以便向注销视图发送额外的上下文。阅读更多关于从 url 定义中向视图传递额外上下文的信息

path(
    'logout/',
    auth_views.LogoutView.as_view(),
    {'extra_context':{'categories': Category.objects.all()}}
),

推荐阅读