在django 1.8

时间:2016-11-16 16:57:55

标签: python django forms django-forms django-1.8

我的django模型允许用户提交表单,即使用户没有提交适当的表单也不会出现错误,这里它允许用户将电子邮件字段留空。由于is_valid,它不会保存到数据库中( )但页面刷新,表格再次变为空白......这是代码

models.py

from django.db import models

class MainForm(models.Model):
    text = models.CharField(max_length=100)
    email = models.EmailField(blank=False)
    name = models.CharField(max_length=100,blank=False)


def __unicode__(self):
    return self.email

forms.py

from django import forms
from .models import MainForm,new_model


class form_MainForm(forms.ModelForm):
    class Meta:
        model = MainForm
        fields = '__all__'

views.py

def view_MainForm(request):

context = {
    "form": form_MainForm
}

if request.method == 'POST' :
    form_instance = form_MainForm(request.POST or None)
    if form_instance.is_valid():
        form_instance.save()
        return render(request,'done.html',{'text':form_instance.cleaned_data.get('email')})

return render(request,'main_form.html',context)

模板 - > main_form.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Main Form</title>
</head>
<body>


<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit"  value="Submit">
</form>




</body>
</html>

2 个答案:

答案 0 :(得分:1)

您的查看功能错误 - 您必须将无效表单传递给上下文以获取错误消息,即:

def view_MainForm(request):    
    if request.method == 'POST' :
        form_instance = form_MainForm(request.POST)
        if form_instance.is_valid():
            form_instance.save()
            # here you should redirect to avoid
            # re-submission of the form on page reload
            # cf https://en.wikipedia.org/wiki/Post/Redirect/Get
            return render(request,'done.html',{'text':form_instance.cleaned_data.get('email')})

    else:
        form_instance = form_MainForm()

    context = {"form": form_instance}
    return render(request,'main_form.html',context)

答案 1 :(得分:0)

选中此链接以在表单https://docs.djangoproject.com/en/1.10/topics/forms/#rendering-form-error-messages中呈现错误,这样可以了解您无法保存数据的原因。 当你发回表格时应该是 context = {&#34; form&#34;:form_MainForm(request.POST)},这将显示表单提交的值