>> > > 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. >
Thanks for your reply. But I found out about save_model(). >From there I have access to the HttpRequest object that contains my >contrib.auth.models.User model. But that seemed to be half the story. class Post(models.Model): def save_model(self, req, obj, form, change): if self.author is None: self.author = req.User Doesn't seem to do the trick. I'm getting error reports telling me author_id can't be null. And indeed if I look in my mysql database I see a author_id column and no author column. Makes sence since author is of the type models.ForeignKey(). Anyway how do I get around this ? Regards, Jonas. -- 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.