Preopulate admin field from registered user

How do I pre-fill the administrator field from the user information that is logged into the system?

I have a model.py:

from django.db import models  
class News(models.Model):  
    title = models.CharField(max_length=65)  
    body = models.TextField()  
    author = models.CharField(max_length=55)  

and I have admin.py:

from django.contrib import admin
from django.contrib.auth.models import User
from newsite.news.models import News
class NewsAdmin(admin.ModelAdmin):
    list_display = ('title','author')
    search_fields = ['title', 'author']
    prepopulated_fields = {'author': (?????)} 
admin.site.register(News, NewsAdmin)

I tried my best to try to figure out how to get the currently registered user into this prepopulated_field for the author.

Any advice would be appreciated. Thank.

+3
source share
1 answer

My models.py:

author = models.ForeignKey(User)

Admin.py:

class BugAdmin( admin.ModelAdmin ):
    fields = ['name', 'slug', 'summary', 'categories', 'status', 'browser', 'frequency', 'really_bug']
    exclude = ('author','excerpt')
    prepopulated_fields = { 'slug' : ['name'] }
    form = BugForm

    def save_form(self, request, form, change):
        obj = super( BugAdmin, self).save_form(request, form, change)
        if not change:
            obj.author = request.user
        return obj
+4
source

Source: https://habr.com/ru/post/1770716/


All Articles