【发布时间】:2020-05-07 14:19:42
【问题描述】:
我对 django 非常陌生,并且在我的第一个项目中。我有多个 ModelForms 要显示在一个带有一个提交按钮的网页中,我希望所有用户输入数据都存储在数据库中。如果表格超过 1 个,forms.save() 似乎不起作用。我如何为此编写视图?
Models.py-
from django.db import models
class PatientBasicInfo(models.Model):
first_name = models.CharField(max_length=200,) # help_text='Enter your Firstname')
last_name = models.CharField(max_length=200,) # help_text='Enter your Lastname')
GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'),)
gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=False)
date_of_birth = models.DateField('DOB', null=True, blank=False)
height = models.FloatField(null=True)
weight = models.FloatField(null=True)
bmi = models.DecimalField(max_digits=10, decimal_places=6, null=True)
ETHNICITY_CHOICES = (('indian', 'INDIAN'), ('asian', 'ASIAN'), ('american', 'AMERICAN'), ('others', 'OTHERS'),)
ethnicity = models.CharField(max_length=15, choices=ETHNICITY_CHOICES,default=False, blank=False)
def __str__(self):
return self.first_name + " " + self.last_name
class MedicalConditions(PatientBasicInfo):
DIABETES_CHOICES = (('I', 'Type1'), ('II', 'Type2'),)
diabetes_type = models.CharField(max_length=2, choices=DIABETES_CHOICES, default=False)
CONDITIONS_CHOICES = (('hBP', 'HYPERTENSION'),
('LBP', 'HYPOTENSION'),
('heart', 'HEARTDISEASE'),
('kidney', 'KIDNEYDISEASE'),
('liver', 'LIVERDISEASE'),
('cancer', 'CANCER'),
('pcod', 'PCOD'),
('pcos', 'PCOS'),
('thyroid', 'THYROID'),)
conditions = models.BooleanField('Medical Conditions', max_length=20, choices=CONDITIONS_CHOICES, null=True, blank=True, default=False)
medications = models.TextField(help_text='Please list the medications you currently take', blank=True)
forms.py:
import datetime
from django import forms
from django.forms import ModelForm
from .models import PatientBasicInfo, MedicalConditions
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
class PatientBasicInfoForm(ModelForm):
#required_css_class = 'required'
def clean_date_of_birth(self):
data = self.cleaned_data['date_of_birth']
if data > datetime.date.today():
raise ValidationError(_('Invalid date'))
return data
class Meta:
model = PatientBasicInfo
fields = ['first_name', 'last_name', 'gender', 'date_of_birth', 'height', 'weight', 'ethnicity']
widgets = {
'gender': forms.RadioSelect, 'ethnicity': forms.Select,
}
class MedicalConditionsForm(ModelForm):
class Meta:
model = MedicalConditions
fields = ['diabetes_type', 'conditions', 'medications']
widgets = {
'diabetes_type': forms.RadioSelect, 'conditions': forms.CheckboxSelectMultiple,
}
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import PatientBasicInfo, MedicalConditions,
from .forms import PatientBasicInfoForm, MedicalConditionsForm
def index(request):
form1 = PatientBasicInfoForm(request.POST or None)
if form1.is_valid():
form1.save()
form2 = MedicalConditionsForm(request.POST or None)
if form2.is_valid():
form2.save()
context = {'form1': form1, 'form2': form2}
return render(request, 'EDApp/Testing.html', context)
def home(request):
return render(request, 'EDApp/home.html')
testing.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TestED</title>
</head>
<body>
<form action="{% url 'home' %}" method="POST">
{% csrf_token %}
{{ form1.as_p }}
{{ form2.as_p }}
<input type="Submit" name="submit" value="Submit"/>
</form>
</body>
</html>
【问题讨论】:
-
显示您的代码。我们需要您的相关表单、视图和模板,最好是最小示例。
-
@TomCarrick 更新了代码。我对编码真的很陌生,所以仍然试图弄清楚基础知识。感谢您的帮助
-
对于
GET和POST请求,尝试使所有视图逻辑相同并不是很好。我不确定这是否是问题的一部分,但是如果您将视图重写为更像这样(但使用两种形式),这将很有用:docs.djangoproject.com/en/3.0/topics/forms/#the-view - 请注意重定向,您应该始终重定向POST 成功后。 -
你能不能也展示一下
PatientBasicInfo和MedicalConditions的模型 -
@TomCarrick 更新了模型。请就我可以使用哪种视图提供您的意见?我希望所有表单都出现在同一个页面中,只有一个提交按钮,所以不确定重定向会有什么帮助。
标签: django django-models django-forms django-views django-templates