Django:如何以表格形式链接模型一对象与模型二?

时间:2019-07-16 02:20:32

标签: django django-models django-forms

我试图以表单的形式链接一个模型对象与其他模型,但最终以无效的表单

Models.py:     病人类(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模型和Ipd模型,该模型可在入院前从Patient那里获取更多信息。所以我想将IPD模型与Patient关联起来以创建新的IPD列表

1 个答案:

答案 0 :(得分:0)

首先,这可能不是错误,但是这是一种普遍接受的做法: 代替

if request.POST:

if request.method == "POST":

此外,在重定向中,您正在将消息放入参数中。我对此不确定,但我认为您也许可以做到

messages.success ...
return redirect("/")

因为我认为您的重定向无效。 我非常怀疑错误会在您执行其他操作之后出现

formtwo = IpdForm(request.POST)

因为request.POST已经显示为None 而是

formtwo = IpdForm()

签出django form docs。 另外,我非常确定您不能在表单中放置外键(在您的情况下为IpdForm和Patient类)。相反,请从表单字段中删除“患者”并执行此操作

if formtwo.isvalid():
    formtwo.user_id = request.user.id

我希望这至少可以有所帮助,并且您可以找出问题所在