[英]How to implement a Django class-based view that is both TemplateView and FormView?
I'm attempting to create a django webpage that uses class-based views. 我正在尝试创建一个使用基于类的视图的django网页。 This webpage needs to have the following features:
该网页必须具有以下功能:
I know how to create a webpage that does number 1 by creating a class that inherits from django.views.generic.TemplateView
. 我知道如何通过创建一个从
django.views.generic.TemplateView
继承的类来创建一个编号为1的网页。 I know how to create a webpage that does number 2 and 3 by creating a class that inherits from django.views.generic.editFormView
. 我知道如何通过创建一个从
django.views.generic.editFormView
继承的类来创建一个数字为2和3的网页。 But I can't figure out how to make a webpage that does all three. 但是我不知道如何制作一个可以同时完成这三个步骤的网页。 I tried creating a class that inherits from both
TemplateView
and FormView
but found that I still couldn't get at the HTTP GET data. 我尝试创建一个同时继承自
TemplateView
和FormView
的类,但发现我仍然无法获取HTTP GET数据。 Please advise how I can make this work. 请告知我如何进行这项工作。
Here is my relevant urls.py
entry: 这是我相关的
urls.py
条目:
url(
r'^myPage/(?P<myArg1>\d+)-(?P<myArg2>\d+)/?$',
myView.as_view(),
name='myName'
),
Here is my view class: 这是我的视图类:
class myView(FormView, TemplateView):
template_name = 'myApp/myTemplate.html'
form_class = myForm
success_url = reverse_lazy("successPage")
def get_context_data(self, **kwargs):
context = super(myView, self).get_context_data(**kwargs)
myArg1 = int(kwargs["myArg1"])
myArg2 = int(kwargs["myArg2"])
# Do some validation and some other interesting stuff here based on
# the values of myArg1 and myArg2 and put the result into self.newArg
self.newArg = myDummyFunction(myArg1, myArg2)
context["form"] = self.form_class
return context
def form_valid(self, form):
formField1 = form.cleaned_data.get('field1')
logger.debug("self.newArg = %s" % self.newArg) # <--- This Fails! self.newArg doesn't exist!
return super(myView, self).form_valid(form)
You're overcomplicating this. 您太复杂了。 FormView - like almost all generic views - already inherits from TemplateView (or rather, from ContextMixin, which includes all the functionality you are after), so there is no need to add that second class in the declaration.
就像几乎所有通用视图一样,FormView已经继承自TemplateView(或者继承自ContextMixin,后者包含您所需要的所有功能),因此无需在声明中添加第二个类。
The only reason your code doesn't work already is that get_context_data is not called when the form is valid - because valid forms always redirect to another view, so there is no reason to get any context data for the current one. 您的代码不起作用的唯一原因是,当表单有效时,不会调用get_context_data -因为有效表单始终会重定向到另一视图,因此没有理由获取当前视图的任何上下文数据。 But you shouldn't need to access that argument inside form_valid at all: you should add it to the context dictionary inside get_context_data, and then you can access it in the template just like any other context variable.
但是您根本不需要在form_valid内部访问该参数:您应该将其添加到get_context_data内部的上下文字典中,然后您就可以像其他任何上下文变量一样在模板中访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.