在保存时在Django的pipe理面板中操作数据
好吧,所以这里是瘦的:
# 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窗体中省略了作者字段。 我想,不知何故,它保存之前自动填充。 我如何做到这一点? 我在Google上呆了最后一个小时,无济于事。
提前致谢。
从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()
class ArticleAdmin( admin.ModelAdmin ): fields = [ 'title', 'body' ] form = ArticleAdminForm def save_model(self, request, obj, form, change): obj.author = "name Here" obj.save()