django模板表单不保存数据

时间:2015-09-14 20:06:39

标签: python django

我有一个模板表单并试图保存一些数据。单击提交按钮后,页面将刷新,并且不会将任何内容保存到数据库中。我没有任何错误。

模板

<form action="" method="post" id="salesform">
         {% csrf_token %}

        <input type="name" class="form-control" id="name" placeholder="Name">
        <input type="clinic" class="form-control" id="clinic_name" placeholder="Clinic">
        <input type="phone" class="form-control" id="phone" placeholder="Phone">
        <input type="email" class="form-control" id="email" placeholder="Email">
        <button id="sub" type="submit" class="btn btn-default">Submit</button>
      </form>

forms.py

class LeadForm(forms.ModelForm):
    name = forms.CharField(max_length=250, required= True,widget=forms.TextInput())
    clinic_name = forms.CharField(max_length=250, required= True,widget=forms.TextInput())
    phone = forms.CharField(max_length=8, required= True,widget=forms.TextInput(attrs={'type':'number'}))
    email = forms.CharField(max_length=250, required= False, widget=forms.TextInput())

    class Meta:
        model = Lead
        fields = ("clinic_name","phone")

views.py

def add_doc_info(request):
    d = getVariables(request,dictionary={'page_name': "Doctors",
    'meta_desc' : "Sign up "})

    if request.method == "POST":
        SalesForm = LeadForm(request.POST)

        if SalesForm.is_valid():
            name = SalesForm.cleaned_data['name']
            clinic_name = SalesForm.cleaned_data['clinic_name']
            phone = SalesForm.cleaned_data['phone']
            email = SalesForm.cleaned_data['email']

            #Saving to database
            lead = Lead(name=name, clinic_name=clinic_name, phone=phone, email=email)
            lead.save()


    else:
        SalesForm = LeadForm()


    return render(request,  'm1/add_doc_info.html', d, context_instance=RequestContext(request))

models.py

class Lead(models.Model):
    name = models.CharField(max_length=1300)
    clinic_name = models.CharField(max_length=1300)
    phone = models.IntegerField()
    email = models.EmailField(blank = True)
    submitted_on = models.DateField(auto_now_add=True)

    def __unicode__(self):
        return u"%s %s" % (self.clinic_name, self.phone)

1 个答案:

答案 0 :(得分:1)

表单几乎无效,但您在模板中没有使用它,因此无法显示错误,也无法使用部分填充的字段重新显示错误。

Django文档对此非常明确,所以我不知道你为什么做了不同的事情。将表单传递到您的上下文中:

d['form'] = SalesForm
return render(request, 'm1/add_doc_info.html', d)

并在模板中使用它:

{{ form.errors }}
<form action="" method="post" id="salesform">
    {% csrf_token %}

    {{ form.name }}
    {{ form.clinic_name }} 
    {{ form.phone }}
    {{ form.email }}
    <button id="sub" type="submit" class="btn btn-default">Submit</button>
</form>

(另请注意,您已经在表单中明确地定义了所有字段,但也表示您只在元类中使用其中的两个字段;而且您的is_valid块通常是不必要的,因为您只需调用{{ 1}}直接。再次,所有这些都在文档中完整显示。)