views:

1017

answers:

3

Hello,

I have a model with a created_by field that is linked to the standard Django User model. I need to automatically populate this with the ID of the current User when the model is saved. I can't do this at the Admin layer, as most parts of the site will not use the built-in Admin. Can anyone advise on how I should go about this?

Thanks for any help

Sean :-)

+2  A: 

This blog entry discusses exactly that.

Farinha
+11  A: 

If you want something that will work both in the admin and elsewhere, you should use a custom modelform. The basic idea is to override the __init__ method to take an extra parameter - request - and store it as an attribute of the form, then also override the save method to set the user id before saving to the database.

def MyModelForm(forms.ModelForm):

   def __init__(self, *args, **kwargs):
       self.request = kwargs.pop('request', None)
       return super(MyModelForm, self).__init__(*args, **kwargs)


   def save(self, *args, **kwargs):
       kwargs['commit']=False
       obj = super(MyModelForm, self).save(*args, **kwargs)
       if self.request:
           obj.user = self.request.user
       obj.save()
Daniel Roseman
I'm unable to figure out how to make the admin to initialize MyModelForm with 'request' object. Is it even possible without modifying the contrib.admin code itself?
jholster
A: 

The 'save' method from forms.ModelForm returns the saved instanced.

You should add one last line to MyModelForm:
...
return obj

This change is necessary if you are using create_object or update_object generic views.
They use the saved object to do the redirect.