On Tue, Feb 15, 2011 at 3:58 PM, Jonas Geiregat <jo...@geiregat.org> wrote: > I have a model > > from django.contrib.auth.models import User > > class Post(models.Model): > with_some_properties = model.CharField(max_length=1) > author = models.ForeignKey(User) > > def clean(self): > if self.author is None: > self.author = ???? > > > When a post is saved I would like to bind the current logged in user the the > self.author field in the clean method. > How could I accomplish this ? > > Regards, > > Jonas. >
Two ways: 1) Pass the form which is creating/modifying this object the current request. It can then use the request object in the save() method to populate the field. Eg: class FooForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(FooForm, self).__init__(*args, **kwargs) def save(commit=False): foo = super(FooForm, self).save(commit=False) if not foo.user: foo.user = request.user if commit: foo.save() return foo Even better would be to not pass around an opaque object which has magic data in it - if you need the current user to correctly create objects, then pass the user to the form which creates the objects. 2) At the start of each request, store the current request in thread local storage[1], so that it is globally available everywhere. You may have noticed I can knock out the implementation to 1) from rote, this is because this is the correct way of doing it. It's harder, more work, and doesn't 'just work', but it means you haven't tied your models to only working within the context of a web request. For instance, if you went the thread local route, and you wanted to run a management command to import data, you would have to prep thread local storage with a dummy 'request' object, providing the 'current user' to your scripts. Cheers Tom [1] http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.