Auto select current user in Django admin form

May 13, 2015 · by Tim Kamanin

For example, we have the following model with an author field and we want automatically set this value to current user in the admin form:

# file:
class Post(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    date = models.DateField()
    author = models.ForeignKey(settings.AUTH_USER_MODEL)

Implement admin class in with following methods:

# file:
class PostAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if == 'author':
            kwargs['queryset'] = get_user_model().objects.filter(username=request.user.username)
        return super(PostAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    def get_readonly_fields(self, request, obj=None):
        if obj is not None:
            return self.readonly_fields + ('author',)
        return self.readonly_fields

    def add_view(self, request, form_url="", extra_context=None):
        data = request.GET.copy()
        data['author'] = request.user
        request.GET = data
        return super(NotesAdmin, self).add_view(request, form_url="", extra_context=extra_context), PostAdmin)

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials