我是 Django (1.5) 的新手,我正在尝试做一个基本的 POST 表单。我有一个TemplateView
实现表单(使用 传递给模板get_context_data
)。
当表单由于某种原因(例如验证错误)失败时,我想再次显示表单,其中包含用户填写的数据。当它成功时,我想重定向到一个成功页面(例如刚刚创建的项目)。
这是我到目前为止所做的:
class WriteForm(forms.Form):
subject = forms.CharField()
text = forms.CharField(widget=forms.Textarea)
# some other stuff
class WriteView(MailboxView):
# MailboxView extends TemplateView and defines some context
template_name = 'messages/write.html'
form_data = None
def post(self, request, *args, **kwargs):
# treat form data...
# lets make things simple and just assume the form fails
# I want to do something like that:
self.form_data = request.POST
# should I return something?
def get_context_data(self, **kwargs):
context = super(WriteView, self).get_context_data(**kwargs)
if self.form_data is None:
context['form'] = WriteForm()
else:
context['form'] = WriteForm(self.form_data)
return context
提前致谢!