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
  • 24,909
  • 20
  • 73
  • 94
a06e
  • 18,594
  • 33
  • 93
  • 169
  • This is too vague. How is the `Package` added? Through form? Through admin? – Shang Wang Aug 28 '15 at 20:12
  • We need more info on a couple of items: (1.) where are you creating it (as Shang Wang said)? (2.) What kind of user? Another model of yours? Subclass of `auth.User`? Some 3rd party package's user model? – Two-Bit Alchemist Aug 28 '15 at 20:12
  • possible duplicate of [In Django, how do I know the currently logged-in user?](http://stackoverflow.com/questions/1477319/in-django-how-do-i-know-the-currently-logged-in-user) – Two-Bit Alchemist Aug 28 '15 at 20:13
  • If you create the object in a view, you could take the user from the request. – Gocht Aug 28 '15 at 20:13
  • @ShangWang through admin. – a06e Aug 28 '15 at 20:53

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
  • 298,606
  • 55
  • 578
  • 516
  • 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*. – a06e 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 – a06e 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