代码之家  ›  专栏  ›  技术社区  ›  fabio

django registration redux中的视图子类

  •  1
  • fabio  · 技术社区  · 7 年前

    我在用 Django-registration-redux 我想给视图提供更多数据来渲染我的基础模板。我读了 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'),
        ...
    ]
    

    我在服务中有额外的数据。py,但此代码给出错误:

    name 'request' is not defined
    

    所以 context_dict 未定义。我可以从哪里接受我的请求?主要是我需要用户(但是 print(user)= 'user' is not defined ). 还是应该编写另一个函数?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Alasdair    7 年前

    在基于Django类的视图的方法中,您可以 access the request 具有 self.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 LoginRequiredMixin 这样,只有登录的用户才能访问该视图,但在您的情况下 PasswordChangeView 帮你解决这个问题。