简体   繁体   中英

Django saving data in model through model form and foreign key

I have a model named Doctor and a model named Appoint which have doctor as a foreign key . and I have a model form to take input for the Appoint model but not for the foreign key in it. I am able to link the Doctor model through url but I am not able to save doctor(foreign key) in Appoint model.

here are the 2 models:-

``` class Doctor(models.Model):
    docid = models.IntegerField(null=True, default=1001)
    name = models.CharField(max_length=40)
    phone = models.IntegerField()
    add = models.TextField()
    email = models.EmailField()
    category = models.CharField(choices=doc_cat,max_length=20)
    price = models.IntegerField()

    def __str__(self):
        return self.name

class Appoint(models.Model):
    f_name = models.CharField(max_length=12)
    l_name = models.CharField(max_length=12)
    phone1 = models.IntegerField()
    phone2 = models.IntegerField()
    add = models.CharField(max_length=100)
    city = models.CharField(max_length=20)
    state = models.CharField(max_length=30)
    pincode = models.IntegerField()
    doctor = models.ForeignKey(Doctor,null=True, on_delete=models.CASCADE)
    day = models.CharField(max_length=30)
    timeslot = models.CharField(max_length=30)
    symptom = models.CharField(max_length=200)
    email = models.EmailField()
    date = models.DateField(auto_now=True)

    def __str__(self):
        return self.f_name + self.l_name```

here is the view method:-

``` def takeappointment(request, docid):
    doctor = Doctor.objects.get(docid = docid)
    if request.method == 'POST':
        form = Appointform(request.POST)
        if form.is_valid():
            form.save()
            f_name = request.POST['f_name']
            l_name = request.POST['l_name']
            day = request.POST['day']
            timeslot = request.POST['timeslot']
            email = request.POST['email']
            return render(request, 'submit.html', {
                'f_name' : f_name,
                'l_name' : l_name,
                'day' : day,
                'timeslot' : timeslot,
                'email' : email,
                })   
    form = Appointform()
    return render(request, 'takeappointment.html', {'form': form, 'doctor': doctor})
 ```

how can save the foreign key from Doctor model along with form data in Appoint model?

you can do it this way: add doctor parameter to your Appointform

class Appointform(forms.ModelForm):
    class Meta:
        model = Appoint

    def __init__(self, *args, **kwargs):
        self.from_doctor = kwargs.pop("from_doctor", None)
        super().__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super().clean()
        cleaned_data["doctor"] = self.from_doctor
        return cleaned_data

and in your takeappointment view add this parameter when create form

def takeappointment(request, docid):
    doctor = Doctor.objects.get(docid = docid)
    if request.method == 'POST':
        form = Appointform(request.POST, from_doctor=doctor)
        if form.is_valid():
            form.save()
            f_name = request.POST['f_name']
            l_name = request.POST['l_name']
            day = request.POST['day']
            timeslot = request.POST['timeslot']
            email = request.POST['email']
            return render(request, 'submit.html', {
                'f_name' : f_name,
                'l_name' : l_name,
                'day' : day,
                'timeslot' : timeslot,
                'email' : email,
                })   
    form = Appointform(from_doctor=doctor)
    return render(request, 'takeappointment.html', {'form': form, 'doctor': doctor})            

you also need to change definition of Appoint model, add blank=True to your doctor field

doctor = models.ForeignKey(Doctor, null=True, blank=True, on_delete=models.CASCADE)

you can do it other way.

class Appointform(forms.ModelForm):
    class Meta:
        model = Appoint
        exclude = ("doctor", )

    def __init__(self, *args, **kwargs):
        self.from_doctor = kwargs.pop("from_doctor", None)
        super().__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.instance.doctor = self.from_doctor
        return super().save(*args, **kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM