[英]Django: How to provide context for a FormView?
Newbie Question: I have a FormView which displays a sign-up form, using Django's validations, etc. It all works fine, however, I can't seem to work out how to provide any data (context) to the template. 新手问题:我有一个FormView,它使用Django的验证等方式显示注册表单。一切正常,但是,我似乎无法弄清楚如何向模板提供任何数据(上下文)。 Currently, I have:
目前,我有:
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/')
I tried adding some context data via get()
per below, which I need when the page first displays, which sort of works except the input fields of the form are gone (the labels are all there): 我尝试通过下面的
get()
来添加一些上下文数据,这是页面首次显示时需要的, 除了表单的输入字段(标签都在这里) 之外 ,该做什么工作:
def get(self, request):
return render(self.request, self.template_name, {'data': data })
Could someone please clarify why that is, and how to get it to work? 有人可以说明为什么是这样,以及如何使其工作吗? To put it another way: When using FormView with form_valid(), where do I place code intended for the initial GET request?
换句话说:将FormView与form_valid()结合使用时,应在哪里放置用于初始GET请求的代码?
You have to methods of doing it, if the data is related only to that get view then you can move on: 您必须采用这种方法,如果数据仅与该获取视图相关,则可以继续:
def get_context_data(self, **kwargs):
context = super(SignUpView, self).get_context_data(**kwargs)
something = something
context['something'] = something
return context
Or use a Mixin: 或使用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
And then: 接着:
class SignUpView(SomeMixin, FormView):
def form_valid(self, form):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.