0

我已经创建了注册表。当我单击提交按钮时,form.is_valid() 返回 false。所以我的数据没有保存。Django 版本:1.4 下面是我的代码:

表格.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

索引.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>

视图.py

def 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))
4

1 回答 1

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))
于 2013-10-31T11:40:29.093 回答