新手问题:我有一个FormView,它显示一个注册表单,使用Django的验证等。一切正常,但是,我似乎无法弄清楚如何向模板提供任何数据(上下文) 。目前,我有:
from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse
from accounts.forms import SignUpForm
class SignUpView(FormView):
template_name = 'accounts/signup.html'
form_class = SignUpForm
def form_valid(self, form):
# executes when form validates..
(...)
return redirect('/account/')
我尝试通过以下get()
添加一些上下文数据,这是我首页显示时所需要的,除了表单的输入字段之外,哪种工作(标签)都在那里):
def get(self, request):
return render(self.request, self.template_name, {'data': data })
有人可以澄清为什么会这样,以及如何让它发挥作用?换句话说:当使用带有form_valid()的FormView时,我在哪里放置用于初始GET请求的代码?
答案 0 :(得分:0)
你必须采用这种方法,如果数据只与该获取视图相关,那么你可以继续:
def get_context_data(self, **kwargs):
context = super(SignUpView, self).get_context_data(**kwargs)
something = something
context['something'] = something
return context
或使用Mixin:
class SomeMixin(object):
def get_context_data(self, **kwargs):
context = super(SomeMixin, self).get_context_data(**kwargs)
something = something
context['something'] = something
return context
然后:
class SignUpView(SomeMixin, FormView):
def form_valid(self, form):
...