如果表单无效,我正在尝试为上下文分配值。这就是我在做的事情。但是如果表格无效,我的回答很奇怪,而且我没有表格。
{'key': 'Val', 'form': <MainLoginForm bound=True, valid=True, fields=(user_name;user_category;user_password)>, u'view': <mainApp.views.MainLoginFormView object at 0x107553c10>} Submit
这是班级
class MainLoginFormView(FormView):
template_name = 'login.html'
form_class = MainLoginForm
success_url = "login.hrml"
args = {}
def ValidateAccount(self,form):
if(valid) #Some Condition to confirm if valid form
return super(MainLoginFormView, self).form_valid(form)
else:
return self.form_invalid(form)
def form_invalid(self, form):
MainLoginFormView.args = super(MainLoginFormView, self).get_context_data(**MainLoginFormView.args)
MainLoginFormView.args["key"] = "Val"
MainLoginFormView.args["form"] = form
#return self.render_to_response(context=MainLoginFormView.args)
return super(MainLoginFormView,self).form_invalid(MainLoginFormView.args)
def form_valid(self, form, **kwargs):
MainLoginFormView.args = kwargs
.....
return self.ValidateAccount(form)
答案 0 :(得分:0)
form_invalid
方法仅作为输入形式。您可以覆盖它以满足您的要求:
您应该将args重命名为kwargs
def form_invalid(self, form):
# Do your your stuff here ,
MainLoginFormView.kargs["key"] = "Val"
MainLoginFormView.kargs["form"] = form
return self.render_to_response(self.get_context_data(**MainLoginFormView.kargs))
答案 1 :(得分:0)
这似乎有点奇怪,但建议将更新响应上下文的责任委托给get_context_data
方法。
def get_context_data(self, **kwargs):
form = kwargs.pop('form', None) # form becomes None if no form key is provided
ctx = super(MainLoginFormView, self).get_context_data(form=form) # This super call will append the form to our context
ctx.update(**kwargs) # Let's append the extra_args to our context
return ctx
def form_invalid(self, form, **kwargs):
# in order to work, the super call to get_context_data needs a form item
kwargs.update({'form': form})
return self.render_to_response(self.get_context_data(**kwargs))
def ValidateAccount(self, form):
if(valid): # A condition to confirm whether the form is valid or not
return super(MainLoginFormView, self).form_valid(form)
else:
extra_args = {
'key': 'Val'
}
return self.form_invalid(form, **extra_args)
注意:{'key': 'Val'}
附加在ValidateAccount方法中。