Django表单未提交

时间:2020-03-08 15:48:45

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

我的django表单在单击“提交”后未提交。我尝试单击按钮以提交信息,但没有任何反应。在终端或Chrome的开发人员中不会显示任何错误或消息。此页面上没有JS,只是html:我在不同的项目上使用了相同的方法,但是这样做不起作用。我的代码可能是什么问题。

models.py
class Department(models.Model):
    depart_code = models.CharField(max_length=20,unique=True)
    depart_name = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return self.depart_name
views.py
class DepartmentAddView(CreateView):
    model = Department
    form_class = DeptAddForm
    template_name = 'hrms/department_form.html'


    def form_valid(self, form):
        form.save()
        return redirect('/')
forms.py
class DeptAddForm(forms.ModelForm):
    depart_name = forms.CharField(
        max_length=100,
        widget=forms.TextInput(
            attrs={
                'class': 'span8',
            }
        ),
        label = "*Department Name",
    )
    departt_code = forms.CharField(
        max_length=100,
        widget=forms.TextInput(
            attrs={
                'class': 'span8',
            }
        ),
        label = "*Department Code",
    )

    class Meta:
        model = Department
        fields = ['depart_code', 'depart_name']
hrms/department_form.html
<form class="form-horizontal row-fluid" method="POST">{% csrf_token %}
    <div class="control-group">
       <label class="control-label" for="basicinput">Department Code</label>
       <div class="controls">
           {{ form.depart_code }}
       </div>
    </div>
    <div class="control-group">
       <label class="control-label" for="basicinput">Department Name</label>
       <div class="controls">
          {{ form.depart_name }}
       </div>
    </div>

    <div class="control-group">
       <div class="controls">
        <button type="submit" class="btn-success">Submit Form</button>
       </div>
    </div>
</form>

2 个答案:

答案 0 :(得分:0)

您的forms.py中有一个错字,您在其中覆盖字段,对于字段depart_code,您写的是departt_code而不是depart_code,这就是导致问题的原因。因此,正确的forms.py应该如下所示:

class DeptAddForm(forms.ModelForm):
    depart_name = forms.CharField(
        max_length=100,
        widget=forms.TextInput(
            attrs={
                'class': 'span8',
            }
        ),
        label = "*Department Name",
    )
    depart_code = forms.CharField(
        max_length=100,
        widget=forms.TextInput(
            attrs={
                'class': 'span8',
            }
        ),
        label = "*Department Code",
    )

    class Meta:
        model = Department
        fields = ['depart_code', 'depart_name']

答案 1 :(得分:0)

再次检查您的views.py文件

本节特别

def form_valid(self, form):
    form.save()
    return redirect('/')    # is this right url ?? (read below)

此重定向将决定提交表单后将重定向到哪个网页,因此请确保urls.py文件中提到此('/')路径,如果没有,请使用正确的路径更改此路径(您的urls.py文件中存在的内容)