2013-10-31 169 views
0

我已經創建了註冊表單。當我點擊提交按鈕時,form.is_valid()返回false。所以我的數據沒有保存。 Django的版本:1.4 下面是我的代碼:django:form.is_valid()總是返回false

forms.py

class RegisterForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs): 
     super(RegisterForm, self).__init__(*args, **kwargs) 
     self.fields['user_type'].required = True 

    class Meta: 
     model=RegisterModel 

的index.html

<form action="/registration/" method="POST"> 
    <table border="0" cellspacing="8" align="center"> 
    <tr> 
     {{form.user_type.errors}} 
     <td> User Type:</td> 
     <td style="text-align:left !important">{{ form.user_type }}</td> 
    </tr> 
    <tr> 
      {{form.pricing_plan.errors}} 
      <td class="align-left" width="85">Pricing Plan:</td> 
      <td width="190" style="text-align:left !important">{{ form.pricing_plan }}</td> 
    </tr> 
    <tr> 
      {{form.full_name.errors}} 
      <td class="align-left">Full Name:</td> 
      <td>{{ form.full_name }}</td>       
    </tr> 
    <div class="submit-reset"> 
      <input type="submit" value="Submit" id="button" class="sub-res-btn"/>&emsp;<input type="Reset" id="button" class="sub-res-btn"/> 
    </div> 
</form> 

views.py

高清user_registration(請求):

if request.method == 'POST': 
    form = RegisterForm(request.POST) 
    print "form is valid or not", form.is_valid() 
    if form.is_valid(): 
     form.save() 
     return HttpResponseRedirect('/marketing/') 
extra_context = {} 
extra_context['form'] = RegisterForm() 
return render_to_response('index.html', extra_context, context_instance=RequestContext(request)) 
+0

嘗試打印'form.errors'看什麼形式的錯誤。你的'RegisterForm'看起來像什麼? – Alasdair

+0

你可以分享'RegisterForm'類嗎? – FallenAngel

回答

2

請勿在表單無效時重置表單,並在模板中顯示{{form.non_field_errors}}

可以更新視圖代碼:

def user_registration(request): 
    extra_context = {} 
    if request.method == 'POST': 
     form = RegisterForm(request.POST) 
     print "form is valid or not", form.is_valid() 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect('/marketing/') 
    else: 
     form = RegisterForm() 

    extra_context['form'] = form 
    return render_to_response('index.html', extra_context, 
        context_instance=RequestContext(request))