1

I have a model, Package:

class Package(models.Model):
    VIP = models.BooleanField()
    name = models.CharField(max_length=200)
    contents = models.CharField(max_length=200)
    owner = # username that created this object

Whenever a user adds a new Package (through admin), I want that the owner to contain the name of this user. How can I do this?

Shang Wang
  • 23,393
  • 19
  • 68
  • 91
becko
  • 15,722
  • 27
  • 80
  • 155

1 Answers1

3

If you want to hide the owner field in the admin, then exclude the owner field from the model admin, and set the owner in the save_model method.

class PackageAdmin(admin.ModelAdmin):
    exclude = ('owner',)

    def save_model(self, request, obj, form, change):
        if not change:
            # only set owner when object is first created
            obj.owner = request.user
        obj.save()

If you want to keep the form's owner field, then override get_changeform_initial_data, and add the owner as an initial value.

class PackageAdmin(admin.ModelAdmin):
    def get_changeform_initial_data(self, request):
        return {'owner': request.user}

The code above assumes that owner is a foreign key to the user model, which is the approach I recommend. If you really want to store the username as a string, then you need to change the lines above to:

obj.owner = request.user.username

return {'owner': request.user.username}
Alasdair
  • 278,338
  • 51
  • 534
  • 489
  • This is a solution. But I don't want to hide the `owner` field from the admin. Instead, I would like that the default value be the user creating the object for the first time. Is there a way to do this? *Please, if you find a way to do this, don't delete the previous answer, as it is useful too*. – becko Aug 31 '15 at 16:00
  • I've added an alternative approach that keeps the owner form field. – Alasdair Aug 31 '15 at 16:13
  • The `get_form` gives me an error: `modelform_factory() got an unexpected keyword argument 'initial'`. Have you tested this? I am using django 1.7 – becko Sep 01 '15 at 15:45
  • No, I haven't tested the code. I've updated the answer, try overriding `get_changeform_initial_data` instead. – Alasdair Sep 01 '15 at 16:11