Search code examples
pythondjangoblogsadmin

Author foreignkey field automatically chosen in admin space of blog app


I have created a blog app which its model has an author field like this:

author = models.ForeignKey(User)

I'm trying to modify default add view in django admin in order to get the added post take the logged first name user. How? This way:

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == 'author':
        kwargs['initial'] = request.user.id
        return db_field.formfield(**kwargs)

    return super(PostAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Well, in add view the select input which corresponds to author field shows the username. I want this select shows first_name + last_name field and not username field. And finally, when i success in this task, i want to hide this select. The logged user must not change the user who sends an entry to the blog.

I have been several hours working on this with no success. Help please!

Thanks a lot mates.


Solution

  • One way to make the author foreign key field show User.first_name + User.last_name is to use a proxy model for the User in author:

    # your_app.models
    from django.contrib.auth.models import User
    
    
    class AuthorUser(User):
        class Meta:
            proxy = True
    
        def __unicode__(self):
            return '%s %s' % (self.first_name, self.last_name)
    
    
    class YourModel(models.Model):
        author = models.ForeignKey(AuthorUser)
    

    To make the field go away, you can simply mark it editable=False. Hope that helps you out.

    Edit: In Django 2.0, you will need an on_delete parameter in order to use ForeignKey.

    class YourModel(models.Model):
        author = models.ForeignKey(AuthorUser, on_delete=models.CASCADE)