AleMal
AleMal

Reputation: 2077

Django auto populate author field in admin panel

In my django project i have a model.py with a class like this:

class temp_main(models.Model):
    descr = models.CharField(max_length=200, verbose_name="Description")
    notes = models.TextField(null=True, blank=True, verbose_name="Note")
    dt = models.DateTimeField(auto_now=True)
    #Fields for API permissions
    owner = models.ForeignKey('auth.User', related_name='tmain_owner', on_delete=models.CASCADE, verbose_name="API Owner")

    class Meta:
       verbose_name = '1-Main Template'
       verbose_name_plural = '1-Main Templates'

    def __str__(self):
        return self.descr

i would that in my admin panel the owner field was auto-populated with the current login user. In my admin.py i write:

admin.site.register(temp_main, )

How can i set my owner field with logged in user?

Thanks in advance

Upvotes: 2

Views: 1561

Answers (1)

briancaffey
briancaffey

Reputation: 2558

I think what you need is the save_model method. Here's how it is used (from the documentation):

from django.contrib import admin
from myproject.myapp.models import Article

class ArticleAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super().save_model(request, obj, form, change)

admin.site.register(Article, ArticleAdmin)

I think you could change obj.user to obj.owner in your case. Does that work?

Also, I think you would want to change the name of the temp_main class to TempMain and then name the class in the admin.py file TempMainAdmin. Django will use this naming scheme to know which Admin Model goes with which model.

Upvotes: 5

Related Questions