单击提交按钮后,为什么值未存储在表中?

时间:2019-05-23 06:54:32

标签: django crud

我创建了一个用于获取值并将其放置在表格中的表格。但是,每当我单击“提交”按钮时,它都不会存储或没有任何错误。它只是停留在该页面本身中。

Model.py
    class Employee(models.Model):
    ename=models.CharField(max_length=120)
    eaddress=models.CharField(max_length=120)
    eemail=models.CharField(max_length=120)
    ephone=models.CharField(max_length=120)
    emobile=models.CharField(max_length=120)
    eid=models.CharField(max_length=120)
    egender=models.CharField(max_length=120)
    ehire=models.DateTimeField()
    edob=models.DateTimeField()

class Meta:
    db_table="employee"
views.py
    def employee(request):
        emp=Employee.objects.all()
        return render(request,'employee.html',{'emp':emp}) 
    def addemployee(request):
        if request.method == 'POST':
            emp = EmployeeForm(request.POST)
            if emp.is_valid():
                try:
                    form.save()
                    return redirect(employee)
                except:
                    pass
        else:
            emp = EmployeeForm()
return render(request,'addemployee.html',{'emp':emp})


addemployee.html:
    <form method="POST" action="add_employee">  
        {% csrf_token %} 
          {{emp.ename}}
          {{emp.eemail}}
          {{emp.emobile}}
    <button type="submit">Submit</button>
    </form>

1 个答案:

答案 0 :(得分:0)

您需要在模板中显示表单错误。因此,像这样更新您的视图和模板:

def addemployee(request):
    emp = EmployeeForm(request.POST or None)
    if request.method == 'POST':
        if emp.is_valid():
            try:
                emp.save()
                return redirect(employee)
            except Exception as e:
                raise e  # for debug purpose now
    return render(request,'addemployee.html',{'emp':emp})


addemployee.html:
<form method="POST" action="add_employee">  
    {% csrf_token %}
      {{ emp.errors }}  // it will render form errors
      {{emp.ename}}
      {{emp.eemail}}
      {{emp.emobile}}
      <button type="submit">Submit</button>
</form>

我假设您的表单未通过验证,因为您有许多字段,例如eidegender等,将其保存在数据库中是必需的。如果您使用的是Modelform,则可以使用{{ emp.as_p }} as per form rendering documentation而不是{{emp.ename}} {{emp.eemail}} {{emp.emobile}}来呈现表单。