I will answer myself. The solution is ModelAdmin.save_model(...) method:


class TaskAdmin(admin.ModelAdmin):
    exclude = ('user', )

    def save_model(self, request, obj, form, change):
        obj.user = request.user
        obj.save()

Martin

On Wed, 18 Aug 2010 02:01:33 +0200, Martin Tiršel <dja...@blackpage.eu> wrote:

Hello,

I need to auto-fill currently logged in user in admin after saving a model, but can not find a solution :( In save method of a model is no access to the HttpRequest object, so I don't know how to get the User.

I found a "solution" with Modelform (http://stackoverflow.com/questions/862522/django-populate-user-id-when-saving-a-model), but this is not working, __init__ method of MyCustomModelForm has no request object in arguments:


class TaskAdmin(admin.ModelAdmin):
     exclude = ('user', )
     form = TaskForm


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

     def save(self, *args, **kwargs):
         kwargs['commit'] = False
         obj = super(TaskForm, self).save(*args, **kwargs)
         if self.request:
             obj.user = self.request.user
         obj.save()

     class Meta:
         model = Task

kwargs in __init__ is empty

Thanks,
Martin

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-us...@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.

Reply via email to