首页 > 解决方案 > Django 视图和 HTML 表单

问题描述

我用 HTML 创建了一个表单,我想将它绑定到一个模型,但我不知道如何通过下拉列表的类型从数据库数据中选择一个表单。(例如,应该已经存储在数据库中的医生和患者的姓名。)

当我通过 django 创建表单时,一切正常,但我对 HTML 很感兴趣。

我收到此错误:

/create_appointment/ 处的 ValueError 无法分配“'患者'”:“Appointment.patient”必须是“Patient”实例。

模型.py

class Appointment(models.Model):
    time_appointment = models.DateTimeField()
    patient = models.ForeignKey(
        Patient, related_name='patient_to_appointment', null=True, on_delete=models.SET_NULL)
    doctor = models.ForeignKey(
        Doctor, related_name='doctor_appointment', null=True, on_delete=models.SET_NULL)
    complaint = models.CharField(max_length=50, null=True, blank=True)

视图.py

   def create_appointment(request):
    if request.method == 'POST':
        datetime = request.POST['datetime']
        patient = request.POST['patient']
        doctor = request.POST['doctor']
        service = request.POST['service']

        appointform = Appointment(
            time_appointment=datetime, patient=patient, doctor=doctor, complaint=service)
        appointform.save()
        return redirect('/appointment')
    return render(request, 'main/f_appointment.html')

html

<body>
  <div class="text-center mt-5">
    <form style="max-width: 480px; margin: auto" method="post">
      {% csrf_token %}

      <p class="hint-text mb-3">Please sign in</p>
      <label class="sr-only" for="datetime"></label>
      <input
        type="datetime-local"
        name="datetime"
        class="form-control"
        placeholder="гггг-мм-дд чч:мм:сс время и дата записи"
        required
        autofocus
      />
      <label for="patient" class="sr-only"></label>
      <input
        type="text"
        name="patient"
        class="form-control mt-2"
        placeholder="пациент"
      />
      <label for="doctor" class="sr-only"></label>
      <input
        type="text"
        name="doctor"
        class="form-control mt-2"
        placeholder="доктор"
      />
      <label for="service" class="sr-only"></label>
      <input
        type="text"
        name="service"
        class="form-control mt-2"
        placeholder="услуга"
      />

      <div class="d-grid gap-2 mt-4">
        <input type="Submit" class="btn btn-primary" value="sign in" />
      </div>
    </form>
  </div>
  <br />
  <br />
  <br />
  <br />
</body>

标签: pythondjango

解决方案


如果你使用ModelForms ,Django 会为你做很多事情。这将遍历关系并提供您需要的大部分功能。


推荐阅读