6/18/2018 - 6:12 PM

Django Current User Form

Auto select current user in Django Admin form.

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: models.py
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 admin.py with following methods:

# file: admin.py
class PostAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == '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)

admin.site.register(Post, PostAdmin)