gpt4 book ai didi

Django FormView 没有表单上下文

转载 作者:行者123 更新时间:2023-12-03 23:44:04 25 4
gpt4 key购买 nike

定义 FormView 派生类时:

class PrefsView(FormView):
template_name = "prefs.html"
form_class = MyForm # What's wrong with this?
def get(self,request):
context = self.get_context_data()
context['pagetitle'] = 'My special Title'
context['form'] = MyForm # Why Do I have to write this?
return render(self.request,self.template_name,context)

我预计该行 context['form'] = MyForm不需要,因为 form_class已定义,但没有它 {{ form }}不会传递给模板。
我做错了什么?

最佳答案

在上下文中,form应该是实例化的表单,而不是表单类。定义 form_class与在上下文数据中包含实例化形式完全分开。

对于您给出的示例,我认为您最好覆盖 get_context_data而不是 get .

def get_context_data(self, **kwargs):
context = super(PrefsView, self).get_context_data(**kwargs)
context['pagetitle'] = 'My special Title'
return context

关于Django FormView 没有表单上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com