48

好的,这是瘦的:

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

如您所见,我在管理员表单中省略了作者字段。我想以某种方式在保存之前自动填充它。我该如何做到这一点?最近一个小时我一直在谷歌上,但无济于事。

提前致谢。

4

2 回答 2

76

来自Django 文档

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

save_model方法被赋予HttpRequest模型实例、ModelForm实例和布尔值,具体取决于它是添加还是更改对象。在这里您可以进行任何保存前或保存后的操作。

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

from django.contrib import admin

class ArticleAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super().save_model(request, obj, form, change)
于 2009-04-15T21:05:53.417 回答
17
class ArticleAdmin( admin.ModelAdmin ):
    fields  = [ 'title', 'body' ]
    form    = ArticleAdminForm

    def save_model(self, request, obj, form, change):
         obj.author = "name Here"
         obj.save()
于 2009-04-15T21:03:30.660 回答