Я новичок в django и в моем первом проекте. У меня есть несколько ModelForms, которые будут отображаться на одной веб-странице с одной кнопкой отправки, и я хочу, чтобы все данные, вводимые пользователем, сохранялись в базе данных. Forms.save () не работает, если форм больше 1. Как мне написать для этого просмотры?
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>