You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django表单POST提交后无数据显示问题求助

Django表单提交后重定向正常但数据不显示问题

我开发的Django项目里有5个同类型表单,其中一个出现异常:表单提交后能正常重定向到列表页,但提交的数据完全不显示。以下是相关代码片段:

views.py

########################## PRESCRIPTION #####################################################
def patients_list(request):
    context = {'patients_list': Prescription.objects.all()}
    return render(request, 'dashboard/patients_list.html', context)


def patients_form(request, id=0):
    if request.method == 'GET':
        if id == 0:
            pform = PatientsForm()
        else:
            prescription = Prescription.objects.get(pk=id)
            pform = PatientsForm(instance=prescription)
        return render(request, 'dashboard/patients_form.html', {'pform': pform})
    else:
        if id == 0:
            pform = PatientsForm(request.POST)
        else:
            prescription = Prescription.objects.get(pk=id)
            pform = PatientsForm(request.POST, instance=prescription)
        if pform.is_valid():
            pform.save()
        return redirect('/list')

urls.py

########################## PRESCRIPTION #####################################################
    path('form', views.patients_form, name='patients_form'),
    path('list', views.patients_list, name='patients_list'),
    path('update_patient/<str:id>/', views.patients_form, name="update_patient"),
    path('patients_delete/<str:id>/', views.patients_delete, name="patients_delete"),
########################## END PRESCRIPTION #####################################################

patients_form.html

<form action="" method="POST">
    {% csrf_token %}
    <div class="form-group">
      {{pform.first_name|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.last_name|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.CNI|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.gender|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.marital_status|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.telephone1|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.telephone2|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.town|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.address|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.occupation|as_crispy_field}}
    </div>
    <div class="form-group">
      {{pform.status|as_crispy_field}}
    </div>
    <div class="row">
      <div class="col md 6">
        <button class="btn btn-success my-4" type="submit"> <i class="flaticon-381-database"> </i> Submit</button>
      </div>
      <div class="col md 6">
        <a href="{% url 'patients_list' %}" class="btn btn-secondary btn-block">Back To List
          <i class="fas fa-stream"></i>
        </a>
      </div>
    </div>
</form>

forms.py

class PatientsForm(forms.ModelForm):

    class Meta:
        model = Prescription
        fields = '__all__'
        labels = {
            'first_name': 'First Name',
            'last_name': 'Last Name'
        }

patients_list.html

{% for prescription in patients_list %}
    <tbody>
      <tr>
        <td>
          <div class="custom-control custom-checkbox">
            <input
              type="checkbox"
              class="custom-control-input"
              id="customCheckBox2"
              required=""
            />
            <label
              class="custom-control-label"
              for="customCheckBox2"
            ></label>
          </div>
        </td>
        <td>{{prescription.id}}</td>
        <td>{{prescription.date_added}}</td>
        <td>{{prescription.first_name}}</td>
        <td>{{prescription.last_name}}</td>
        <td>{{prescription.age}}Years</td>
        <td>{{prescription.doctor}}</td>
        <td>{{prescription.town}}</td>
        <td>{{prescription.gender}}</td>
        <td>
          {% if prescription.status == 'New Patient' %}
          <span class="badge badge-outline-primary">
            <i class="fa fa-circle text-primary mr-1"></i>
            {{prescription.status}}
          </span>
          {% elif prescription.status == 'In Treatement' %}
          <span class="badge badge-warning light">
            <i class="fa fa-circle text-warning mr-1"></i>
            {{prescription.status}}
          </span>
          {% elif prescription.status == 'Recovered' %}
          <span class="badge badge-info light">
            <i class="fa fa-circle text-info mr-1"></i>
            {{prescription.status}}
          </span>
          {% endif %}
        </td>
        <td>
            <a href="{% url 'update_patient' prescription.id %}" class='btn text-secondary px-0'>
                <i class="fa fa-pencil fa-fw"></i> Edit 
            </a>
        </td>
        <td>
          <form action="{% url 'patients_delete' prescription.id %}" method='post' class='d-inline'>
            {% csrf_token %}
            <button class="btn text-warning px-0" type="submit"><i class="fa fa-trash-o fa-fw"></i> Delete
            </button>
          </form>
        </td>
      </tr>
    </tbody>
{% endfor %}

排查与修复方案

1. 补充表单遗漏的必填字段

观察列表页渲染的字段,age和doctor在表单中没有对应的输入项,但PatientsForm设置了fields='__all__',如果这两个字段是模型的必填项(未设置blank=True),表单会验证失败,导致数据无法保存。

解决方法:
在patients_form.html中添加这两个字段的输入:

<div class="form-group">
  {{pform.age|as_crispy_field}}
</div>
<div class="form-group">
  {{pform.doctor|as_crispy_field}}
</div>

或者修改模型,将这两个字段设为可选:

# models.py中对应的字段
age = models.IntegerField(blank=True, null=True)
doctor = models.CharField(max_length=100, blank=True, null=True)

2. 显示表单验证错误

当前代码中,无论表单是否验证通过都会直接重定向,无法看到错误信息。修改views.py的POST分支:

else:
    if id == 0:
        pform = PatientsForm(request.POST)
    else:
        prescription = Prescription.objects.get(pk=id)
        pform = PatientsForm(request.POST, instance=prescription)
    if pform.is_valid():
        pform.save()
        return redirect('/list')
    # 表单无效时返回页面并显示错误
    return render(request, 'dashboard/patients_form.html', {'pform': pform})

3. 修正URL参数类型

主键默认是整数类型,URL中使用<str:id>可能导致类型不匹配,改为<int:id>:

path('update_patient/<int:id>/', views.patients_form, name="update_patient"),
path('patients_delete/<int:id>/', views.patients_delete, name="patients_delete"),

4. 修复列表页HTML结构

循环中重复生成<tbody>是无效的HTML结构,将<tbody>移到循环外:

<tbody>
{% for prescription in patients_list %}
  <tr>
    <!-- 原表格内容 -->
  </tr>
{% endfor %}
</tbody>

内容的提问来源于stack exchange,提问作者Loic Fieze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:15:30