2017-01-16 70 views
0

我想爲表單無效的情況下分配一個值。這就是我正在做的。然而,如果表格無效,我的回覆很奇怪,我也沒有表格。form_invalid FormView設置上下文

{'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

form_invalid方法只需要形式作爲輸入。你可以重寫它來滿足你這樣的要求:

您應該重命名參數傳遞給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)) 
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) #Some Condition to confirm if valid form 
     return super(MainLoginFormView, self).form_valid(form) 
    else: 
     extra_args = { 
      "key": "Val" 
     } 
     return self.form_invalid(form, **extra_args) 

注:{'key': 'Val'}在ValidateAccount方法追加。

相關問題