Django: How to get and save a foreign key field in POST method

Viewed 502

I am try to save a data in two models Booking and Event. The first one working well but I get error in the Event, I don't know how to get and save the foreign key data. This is my Event model:

class Event(models.Model):
    def __str__(self):
        return self.title
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField(blank=True, null=True)
    place = models.CharField(max_length=200,blank=True)
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE, blank=True,null=True)
    doctor = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True)

And this is my views:

def registerBooking(request):
    if request.method == 'POST':
        form = BookingForm(request.POST)
        place = request.POST.get('place','')
        visit_type = request.POST.get('visit_type','')
        description = request.POST.get('description','')
        patient = request.POST.get('patient','')
        doctor = request.POST.get('doctor','')
        created_at = request.POST.get('created_at','')
    

        if form.is_valid():
            new_booking = form.save()
            new_event = Event(title=visit_type,description=description,start_time=created_at,place=place,patient=patient,doctor=doctor)
            new_event.save()
            return JsonResponse({"msg":"Booking and Event successfully saved."})
            #return redirect(reverse('dashboard'))
        else:
            return JsonResponse({"msg":"Invalid data"})
    else:
        form = BookingForm()
    return render(request, 'patient/register_booking.html', {'form':form})

new_booking is working but the problem is in new_event, I get this error: "ValueError: Cannot assign "'1'": "Event.patient" must be a "Patient" instance."

1 Answers

I gues you get this error because you got pk of Patient in patient variable, and Django wait Patient instance when save.

You can get Patient instance with patient = Patient.objects.filter(pk = request.POST.get('patient','')).first() and then use it on creating Event

If there is no Patient with pk you got in request.POST you will get None in patient, and after creating Event, patient field in it will be None as well

Same for Doctor instance

Related