Amistad
Amistad

Reputation: 7400

Display owner of a post in django admin list display

My model is like this :

class Activity(models.Model):
    sub_choice = ((1, 'English'), (2, 'Math'),
                  (3, 'Physics'), (4, 'Chemistry'))
    subject = models.IntegerField(choices=sub_choice, default=1, max_length=50)
    hours = models.IntegerField(verbose_name='Time spent in hours', default=0)

My admin.py looks like this :

class ActivityAdmin(ModelAdmin):
    list_display = ('subject', 'hours')

admin.site.register(Activity, ActivityAdmin)

In my list display,I also want the First name of the user who created a certain activty.How do I do this without explicitly asking the creator of the activity to put their name in the form.Is there any way to get this information using a custom function from the User model ?

Upvotes: 0

Views: 629

Answers (1)

wolendranh
wolendranh

Reputation: 4292

Try to use User model.

models.py

from django.contrib.auth.models import User

    class Activity(models.Model):
        sub_choice = ((1, 'English'), (2, 'Math'),
                      (3, 'Physics'), (4, 'Chemistry'))
        subject = models.IntegerField(choices=sub_choice, default=1, max_length=50)
        hours = models.IntegerField(verbose_name='Time spent in hours', default=0)
        owner = models.ForeignKeyField(User)

admin.py

    class ActivityAdmin(ModelAdmin):
        list_display = ('subject', 'hours', 'owner')
        exclude = ['owner']

        def save_model(self, request, obj, form, change):
            """
            Given a model instance save it to the database.
            """
            obj.owner = request.user
            obj.save()

admin.site.register(Activity, ActivityAdmin)

Upvotes: 1

Related Questions