@method_decorator(login_required, name='dispatch')
class BaseView(TemplateView):
template_name = '...html'
def dispatch(self, request, *args, **kwargs):
# ...
return super(BaseView, self).dispatch(request, *args, **kwargs)
class ConfigureView(BaseView):
form_class = Form
template_name = 'configure.html'
def get(self, request, *args, **kwargs):
form = self.form_class(user=request.user)
return render(request, self.template_name, {
'form': form
})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST, user=request.user)
if form.is_valid():
form.save()
return redirect('...')
return render(request, self.template_name, {'form': form})
def get_context_data(self, **kwargs):
print('**********') # Never printed
context = super(ConfigureView, self).get_context_data(**kwargs)
context['app'] = App.objects.get(slug=kwargs['slug'])
return context
为什么呢?我想我正在关注文档。
答案 0 :(得分:3)
您在render
方法中返回.get()
,此方法(render
)接收上下文作为参数,它不会调用.get_context_data()
,您需要这样做:
...
get(self, request, *args, **kwargs):
# ...
return super(ConfigureView, self).get(request, *args, **kwargs)
答案 1 :(得分:-1)
您可以实例化该类,并调用方法
ConfigureView().get_context_data()
或
instance = ConfigureView()
instance.get_context_data()
应该进入打印命令