How to auto insert the current user when creating an object in django admin?


Question

I have a database of articles with a

submitter = models.ForeignKey(User, editable=False)

Where User is imported as follows:

from django.contrib.auth.models import User. 

I would like to auto insert the current active user to the submitter field when a particular user submits the article.

Anyone have any suggestions?

1
25
12/19/2015 10:17:38 AM

Accepted Answer

Just in case anyone is looking for an answer, here is the solution i've found here: http://demongin.org/blog/806/

To summarize: He had an Essay table as follows:

from django.contrib.auth.models import User

class Essay(models.Model):
    title = models.CharField(max_length=666)
    body = models.TextField()
    author = models.ForeignKey(User, null=True, blank=True)

where multiuser can create essays, so he created a admin.ModelAdmin class as follows:

from myapplication.essay.models import Essay
from django.contrib import admin

class EssayAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')
    fieldsets = [
        (None, { 'fields': [('title','body')] } ),
    ]

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()
39
6/7/2010 6:39:09 PM

Let's say that user B saves a record created by user A. By using this approach above the record will be saved with user B. In some scenarios this might not be the best choice, because each user who saves that record will be "stealing" it. There's a workaround to this, that will save the user only once (the one who creates it):

models.py

from django.contrib.auth.models import User

class Car(models.Model):
    created_by = models.ForeignKey(User,editable=False,null=True,blank=True)
    car_name = models.CharField(max_length=40)

admin.py

from . models import *

class CarAdmin(admin.ModelAdmin):
    list_display = ('car_name','created_by')
    actions = None

    def save_model(self, request, obj, form, change):
        if not obj.created_by:
            obj.created_by = request.user
        obj.save()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon