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.
From the Django Docs:
ModelAdmin.save_model(self, request, obj, form, change)
The
save_model
method is given theHttpRequest
, a model instance, aModelForm
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()