a06e
a06e

Reputation: 20774

Automatically fill a field with the name of the user that creates the object?

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?

Upvotes: 1

Views: 396

Answers (1)

Alasdair
Alasdair

Reputation: 308999

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}

Upvotes: 3

Related Questions