python - 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>
解决方案
如果你使用ModelForms ,Django 会为你做很多事情。这将遍历关系并提供您需要的大部分功能。
推荐阅读
- batch-file - 如何将一个字符串批量拆分为多个不同的变量
- java - 连接字符串中的 Spring Profiles
- python - 如何更改 Altair boxplot 信息框以显示平均值而不是中位数?
- spring-boot - 仅当存在 @EnableScheduling 时才制作 bean
- java - 我如何创造一个条件,可以结合计划中的上述计划,并添加他们的价格?
- sql - 带有 if-else 逻辑的 SQL 查询
- arrays - Swift 5 - 显示带有对象数组的嵌套 JSON
- react-native - 导入其他文件时出现反应本机错误
- python - Python 中的一切都是对象,并且每个对象都实现为字典,这是真的吗?甚至是内置类型?
- firebase - Fetch collection startAfter documentID