在Save上操作​​Django管理面板中的数据

时间:2009-04-15 21:00:31

标签: django django-admin foreign-keys save

好的,所以这里是瘦的:

# 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 )

如您所见,我在Admin窗体中省略了author字段。我想以某种方式在保存之前自动填充它。我该如何做到这一点?我在谷歌的最后一小时都无济于事。

提前致谢。

2 个答案:

答案 0 :(得分:59)

来自Django Docs

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

save_model方法被赋予HttpRequest,模型实例,ModelForm实例以及基于添加或更改对象的布尔值。在这里,您可以执行任何保存前或保存后操作。

     

例如,在保存之前将request.user附加到对象:

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

答案 1 :(得分:16)

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

    def save_model(self, request, obj, form, change):
         obj.author = "name Here"
         obj.save()