Milano Slesarik Milano Slesarik - 4 months ago 8
Python Question

How to set current user to be an attribute of the ModelForm?

I have a form which creates a

Reservation
object. This object has a
customer = models.ForeignKey(User)
- which is a required attribute.

What to do to be able to create object using
ReservationCreationForm().save()
?

I've tried to overwrite save method:

def save(self,user,*args,**kwargs):
self.customer = user
super(ReservationCreationForm).save()


so I could create a form with
request.user
attribute but it not works - Exception Value:

'super' object has no attribute 'save'


What would you do?

EDIT

According to todor's answer, I've changed the save to

def save(self,user,*args,**kwargs):
self.customer = user
super(ReservationCreationForm, self).save(*args, **kwargs)


Which solved problem with save() itself but it still does not add
user
to the
Reservation
so it raises Exception Value:

va_app_reservation.customer_id may not be NULL

Answer

Your are not calling the .save method correctly. super accepts a second argument which is the object instance.

super(ReservationCreationForm, self).save(*args, **kwargs)

UPDATE

You are not setting customer to a reservation instance, but to a form instance, that's why your reservation object does not have a customer.

try with this one, (and don't forget the return):

def save(self, user, *args,**kwargs):
    self.instance.customer = user 
    return super(ReservationCreationForm, self).save(*args, **kwargs)