2

I have a model with field:

class MyModel(models.Model):
    name = models.CharField(max_length=50)
    created_by = models.ForeignKeyField(User)

In my admin:

class MyModelAdmin(admin.ModelAdmin):
    list_display= ("name",)
    fields = ("name",)

Here I don't want created_by in admin while adding MyModel. I want it to be set to current user like created_by = request.user

How can I do this?

Thank you

Alasdair
  • 298,606
  • 55
  • 578
  • 516
gamer
  • 5,673
  • 13
  • 58
  • 91
  • possible duplicate of [How to auto insert the current user when creating an object in django admin?](http://stackoverflow.com/questions/2991365/how-to-auto-insert-the-current-user-when-creating-an-object-in-django-admin) – jgadelange Jul 12 '15 at 10:25

2 Answers2

7

You have already set fields so that created_by does not appear in form in the Django admin.

Now you need to override save_model, and set the user before saving new objects.

class MyModelAdmin(admin.ModelAdmin):
    fields = ("name",)

    def save_model(self, request, obj, form, change):
        if not change:
            # the object is being created, so set the user
            obj.created_by = request.user
        obj.save()
Alasdair
  • 298,606
  • 55
  • 578
  • 516
0

To do that override the save_model method and set the created_by field to the current user.

class MyModelAdmin(admin.ModelAdmin):
    list_display= ("name",)
    fields = ("name",)

    def save_model(self, request, obj, form, change):             
        if not change: 
        # can use this condition also to set 'created_by'    
        # if not getattr(obj, 'created_by', None):            
            obj.created_by = request.user
        obj.save()
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
  • I didnt see user in my form. When I try to save without created_by it gives error that is this field is required – gamer Jul 12 '15 at 10:55
  • @Alasdair updated it to check if `obj` has `created_by` attribute set. – Rahul Gupta Jul 12 '15 at 10:58
  • @gamer Try adding `null=True` and `blank=True` to `created_by`. – Rahul Gupta Jul 12 '15 at 11:24
  • The line in the comment `if not getattr(self, 'created_by', None)` won't work, because `self` is the `ModelAdmin` instance, not the object. You could test `if obj.created_by` instead, but that's not quite the same as testing whether the object is being created. – Alasdair Jul 12 '15 at 11:41
  • Sorry it was `obj` above. Updated the ans and yes checking via `created` is better. – Rahul Gupta Jul 12 '15 at 11:47