在 django-registration-redux 中子类化视图

Subclass a view in django-registration-redux

我正在使用 Django-registration-redux and I want give more data to a view to render my base template. I read the example in doc

我的url.py:

class MyPasswordChangeView(PasswordChangeView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # context['book_list'] = Book.objects.all() # example in doc
        context_dict = services.get_base_data_for_views(request)
        return context_dict

urlpatterns = [
    ...
    path('accounts/password/change/', MyPasswordChangeView.as_view(
    success_url=reverse_lazy('auth_password_change_done')), name='auth_password_change'),
    ...
]

我在 services.py 中有额外的数据,但是这段代码给出了错误:

name 'request' is not defined

因此 context_dict 未定义。我可以从哪里获取我的请求?主要是我需要用户(但 print(user)= 'user' is not defined)。还是我应该再写一个函数?

在基于 Django class 的视图的方法中,您可以 access the requestself.request

class MyPasswordChangeView(PasswordChangeView):
    def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context_dict = services.get_base_data_for_views(self.request)

    return context_dict

因此您可以访问 self.request.user 的用户。通常您会希望使用 login_required or LoginRequiredMixin 以便只有登录用户才能访问该视图,但在您的情况下 PasswordChangeView 会为您处理。