Manipulating Data in Django's Admin Panel on Save

Collin Klopfenstein picture Collin Klopfenstein · Apr 15, 2009 · Viewed 30.7k times · Source

Ok, so here's the skinny:

# models.py
class Article( models.Model ):
    title           = models.CharField( max_length = 255 )
    author          = models.ForeignKey( User )
    published_at    = models.DateTimeField( auto_now_add = True )
    body            = models.TextField( )

    def __unicode__( self ):
        return self.title

# admin.py
from hpccoe.news.models import Article
from django.contrib import admin
from django import forms
from django.forms import widgets

class ArticleAdminForm( forms.ModelForm ):    
    title   = forms.CharField( max_length = 255, required = True )
    body    = forms.CharField( required = True, widget = widgets.Textarea )

class ArticleAdmin( admin.ModelAdmin ):
    fields  = [ 'title', 'body' ]
    form    = ArticleAdminForm

admin.site.register( Article, ArticleAdmin )

As you can see, I'm omitting the author field in the Admin form. I want to, somehow, auto-fill this before it's saved. How do I make that happen? I've been on Google for the last hour to no avail.

Thanks in advance.

Answer

Jonathan Lukens picture Jonathan Lukens · Apr 15, 2009

From the Django Docs:

ModelAdmin.save_model(self, request, obj, form, change)

The save_model method is given the HttpRequest, a model instance, a ModelForm instance and a boolean value based on whether it is adding or changing the object. Here you can do any pre- or post-save operations.

For example to attach request.user to the object prior to saving:

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