无法在数据库-Django中保存表单数据

时间:2017-10-04 20:31:34

标签: django django-models django-forms django-views

我正在尝试创建一个简单的表单,它将名称和电子邮件作为用户输入。 但是在我提交之后,它没有被保存在数据库中 manage.py dumpdata显示[],即空行。 请帮忙!

models.py

class EmpD(models.Model):
    name = models.CharField(max_length=100)
    email=models.CharField(max_length=100) 

forms.py

class SubmitF(forms.ModelForm):
    name = forms.CharField()
    email= forms.CharField()
    class Meta:
        model = EmpD
        fileds = '_all_'

views.py

def submit_view(request):
template_name = 'emp/home.html'
redirect_url = 'emp/su.html'
form = SubmitF()

if request.method == 'POST':
    form = SubmitF(request.POST)
    if form.is_valid():
       form.save()

       return HttpResponseRedirect(redirect_url)
else:
    return render(request, template_name, {'form': form})

def index(request):
return render(request, 'emp/home.html')

包含表格的HTML:

<form action='' method="post" >

{% csrf_token %}
{{ form }}

<table border="0" cellpadding="5" cellspacing="0">
<tr> <td style="width: 50%">
<label for="Name"><b>First name *</b></label><br />
<input name="Name" type="text" maxlength="50" style="width: 260px" />
</td> <td style="width: 50%">

</td> </tr> <tr> <td colspan="2">
<label for="Email_Address"><b>Email *</b></label><br />
<input name="Email_Address" type="text" maxlength="100" style="width: 535px" 
/>
</td> </tr> <tr> <td colspan="2">



<input  type="submit" value="Submit Data" />

</td> </tr>
</table>
</form>

app urls.py

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.submit_view, name='submit_view')]

1 个答案:

答案 0 :(得分:0)

建模,单独的表单字段和单个表单的3个视图是非常糟糕的方法。 试试这个。定义简单模型。对于电子邮件输入,定义电子邮件字段,表单本身进行验证。

Models.py

class EmpD(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(null=True, blank=True)

定义forms.py,如果要包含模型字段,只需fields='__all__'为您完成, 否则以此形式定义其他字段

forms.py

class SubmitF(forms.ModelForm):
    class Meta:
        model = EmpD
        fields = '__all__'

简单的views.py,如果请求方法是Get,表单呈现和In Post请求,则传递给服务器的数据。

def submit_view(request):
    template_name = 'path_to_html'
    redirect_url = 'your_url'
    form = SubmitF()

    if request.method == 'POST':
        form = SubmitF(request.POST)
        if form.is_valid():
           form.save()
           return HttpResponseRedirect(redirect_url)
    else:
        return render(request, template_name, {'form': form})

模板结构

<form action="/your-name/" method="post">
    <label for="name">Your name: </label>
    <input id="id_name" type="text" name="name" value="{{ current_name }}">
    <input type="submit" value="OK">
</form>