我正在尝试以django形式创建一对多关系,其中我创建了一个具有id的客户,并且我想使用该客户的信息来创建新表单
models.py 从django.db导入模型
# Create your models here.
class Patient(models.Model):
name = models.CharField(max_length=200);
phone = models.CharField(max_length=20);
address = models.TextField();
Patient_id = models.AutoField(primary_key=True);
Gender = models.CharField(max_length=50);
class Ipd(models.Model):
Presenting_complaints = models.CharField(max_length=300);
Reason_admission = models.CharField(max_length=300);
patient = models.ForeignKey('Patient',on_delete=models.CASCADE
forms.py 从django.forms导入ModelForm 从Django导入表格 从.models import Patient,Ipd
class PatientForm(ModelForm):
OPTIONS = (
('',''),
('Doctor1','Doctor1'),
('Doctor2','Doctor2'),
)
OPTIONS2 = (
('Male', 'Male'),
('Female', 'Female'),
)
Gender= forms.TypedChoiceField(required=False, choices=OPTIONS2,
widget=forms.RadioSelect)
consultant = forms.ChoiceField(choices=OPTIONS)
class Meta:
model = Patient
fields = ['name','phone','address','Patient_id','consultant','Gender']
class IpdForm (ModelForm):
patient = Patient.objects.all()
class Meta:
model = Ipd
fields = ('Presenting_complaints','Reason_admission', 'patient')
def save(self, commit=True):
instance = super().save(commit)
# set Car reverse foreign key from the Person model
instance.patient_set.add(self.cleaned_data['patient'])
return instance
views.py
@login_required
def new(request):
if request.POST:
form = PatientForm(request.POST)
if form.is_valid():
if form.save():
return redirect('/', messages.success(request, 'Patient is
successfully created.', 'alert-success'))
else:
return redirect('/', messages.error(request, 'Data is not
saved', 'alert-danger'))
else:
return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger'))
else:
form = PatientForm()
return render(request, 'new.html', {'form':form})
我想用主键链接两种形式