Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Form save method

I have a form, working off different models and using a through (intermediate) model:

class CourseBooking(BaseModel):
    '''Intermediary model linking a person on a course with the related booking'''

    course = ForeignKey('ScheduledCourse')
    customer = ForeignKey('Customer')
    booking = ForeignKey('GroupBooking', blank=True, null=True)

The form is using a basic form instead of Model form, with the fields added in manually:

class CourseBookingForm(Form):

    course = ModelChoiceField(queryset=ScheduledCourse.objects.all())    
    title = CharField(
            max_length=255,
            widget=Select(choices=TITLE_CHOICES),
            required=False
            )
    gender = CharField(
            max_length=255,
            widget=Select(choices=GENDER_CHOICES),
            required=False
            )
    first_name = CharField(max_length=255)
    surname = CharField( max_length=255)
    dob = DateField(required=False)    
    medical = CharField(required=False, widget = forms.Textarea(attrs={'rows': '4'}))
    # miscellaneous notes
    notes = CharField(required=False, widget = forms.Textarea(attrs={'rows': '4'}))
    email = EmailField(required=False)
    phone = CharField(required=False)
    address = CharField(
            max_length=8188,
            widget=Textarea(attrs={'rows':'4', 'cols':'50'}),
            required=False)
    city = CharField(max_length=255, required=False)
    county = CharField(
            max_length=255, widget=Select(choices=COUNTY_CHOICES))
    postcode = CharField(max_length=255, required=False)
    country = CharField(
            max_length=255,
            widget=Select(choices=COUNTRIES), required=False)

I want to create a save method in the forms.py which will save to the database. What I have at the moment (which is wrong) is and gives the error: IntegrityError: null value in column "customer_id" violates not-null constraint

def save(self):

    data = self.cleaned_data

    if self.cleaned_data['course']:
        crs = self.cleaned_data['course']
        course_booking = CourseBooking(course=crs)
    course_booking.save()

    course = CourseBooking.objects.create(course=data['course'])
    course.save()

    cust = Customer.objects.create(title=data['title'],
                                   gender=data['gender'],
                                   first_name=data['first_name'],
                                   surname=data['surname'],
                                   dob=data['dob'],
                                   notes=data['notes'],
                                   medical=data['medical'],
                                   content_object=cust,
                                   )
    cust.save()

    address = Address.objects.create(address=data['address'],
                      city=data['city'],
                      county=data['county'],
                      postcode =data['postcode'],
                      country=data['country'],
                      content_object=address,
                      )
    address.save()

    email = Email.objects.create(email=data['email'],
                                 content_object=email)
    email.save()

    phone = Phone.objects.create(number=data['phone'],
                  content_object=phone)
    phone.save()
like image 832
Stephen Avatar asked Oct 22 '25 04:10

Stephen


1 Answers

Just call the code for creation of the course object after creating the customer object.

The issue is, the ForeignKey customer in Course model is required, and you have not set that field while creating the object.

You have a couple of other minor issues which I have fixed in the code. .

def save(self):
    data = self.cleaned_data

    course_booking = None
    if self.cleaned_data['course']:
        crs = self.cleaned_data['course']
        course_booking = CourseBooking(course=crs)
        course_booking.save()

    cust = Customer.objects.create(title=data['title'],
                                   gender=data['gender'],
                                   first_name=data['first_name'],
                                   surname=data['surname'],
                                   dob=data['dob'],
                                   notes=data['notes'],
                                   medical=data['medical'],
                                   content_object=cust,
                                   )
    #cust.save()

    course = CourseBooking.objects.create(course=data['course'], customer = cust)
    if course_booking:
        course.booking = course_booking

    #course.save()

    address = Address.objects.create(address=data['address'],
                      city=data['city'],
                      county=data['county'],
                      postcode =data['postcode'],
                      country=data['country'],
                      content_object=address,
                      )
    #address.save()

    email = Email.objects.create(email=data['email'],
                                 content_object=email)
    #email.save()

    phone = Phone.objects.create(number=data['phone'],
                  content_object=phone)
    #phone.save()

On another note, I would put this object creation logic in the view, rather than the model_form's save method.

like image 132
karthikr Avatar answered Oct 23 '25 20:10

karthikr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!