Snippet: 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 admin form:
1
2
3
4
5
6
  1. # file: models.py
  2. class Post(models.Model):
  3. title = models.CharField(max_length=255)
  4. content = models.TextField()
  5. date = models.DateField()
  6. author = models.ForeignKey(settings.AUTH_USER_MODEL)
Implement admin class in admin.py with following methods:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
  1. # file: admin.py
  2. class PostAdmin(admin.ModelAdmin):
  3. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  4. if db_field.name == 'author':
  5. kwargs['queryset'] = get_user_model().objects.filter(username=request.user.username)
  6. return super(PostAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
  7. def get_readonly_fields(self, request, obj=None):
  8. if obj is not None:
  9. return self.readonly_fields + ('author',)
  10. return self.readonly_fields
  11. def add_view(self, request, form_url="", extra_context=None):
  12. data = request.GET.copy()
  13. data['author'] = request.user
  14. request.GET = data
  15. return super(NotesAdmin, self).add_view(request, form_url="", extra_context=extra_context)
  16. admin.site.register(Post, PostAdmin)