我正在使用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'),
...
]
我在services.py中有额外的数据,但是这段代码给出了错误:
name 'request' is not defined
因此context_dict
尚未定义。我在哪里可以接受我的请求?主要是我需要用户(但print(user)= 'user' is not defined
)。或者我应该写另一个函数吗?
答案 0 :(得分:1)
在基于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
会为您处理此问题。