如何在Django的模型2中使用模型一的对象?

时间:2019-07-15 18:57:18

标签: django django-models django-forms

我创建了一个用于创建用户使用表单的模型。我想在模型2中使用模型1中的模型对象来创建新的用户ID

Models.py:

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(choices=GENDER,max_length=10)
    consultant = models.CharField(choices=CONSULTANT,max_length=20)
    def __str__(self):
        return self.name 

class Rooms(models.Model):
    name = models.CharField(max_length=200)
    room_num = models.IntegerField()
    def __str__(self):
        return str(self.name)

class Ipd(models.Model):

    reason_admission = models.CharField(max_length=200, blank=False)
    presenting_complaints = models.CharField(max_length=200,)
    ipd_id = models.AutoField(primary_key=True)
    rooms = models.OneToOneField(Rooms,on_delete=models.CASCADE, 
    blank=False)
    investigation = models.CharField(max_length=300)
    patient = models.ForeignKey(Patient,on_delete=models.CASCADE,null = 
    False)

Forms.py:

from .models import Patient,Ipd


class PatientForm(forms.ModelForm):


    class Meta:
        model = Patient
        fields = 
    ['name','phone','address','Patient_id','consultant','Gender']

class IpdForm(ModelForm):

    class Meta:
        model = Ipd

        fields = ['patient','reason_admission','presenting_complaints', 
        'rooms','investigation']

views.py:

@login_required
def ipd (request,patient_id):
    patient = Patient.objects.get(pk=patient_id)
    if request.POST:

        data = dict(request.POST)
        data['patient']=Patient.Patient_id
        formtwo = IpdForm(request.POST)
        if  formtwo.is_valid():
            if formtwo.save():
                return redirect('/', messages.success(request, 'Patient is successfully updated.', '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:
        formtwo = IpdForm(request.POST)
        return render(request, 'newipd.html', {'form2':formtwo ,'form':patient})

我想使用Patient Model和Ipd Model创建新的ipd_id,但我以无效表格结尾

0 个答案:

没有答案