在Django中使用管理站点

时间:2016-06-09 08:14:23

标签: django django-admin

我有一个带有两个日期字段的模型,用于提交和发布,以及一个用于已批准的布尔字段。

class BlogModel(models.Model):
    title = models.CharField(max_length=100)
    article = models.CharField(max_length=255)
    pub_date = models.DateTimeField('date published')
    submitted_date = models.DateTimeField('date submitted')
    author = models.CharField(max_length=255)
    approved = models.BooleanField(default=False)
    def __str__(self):              # __unicode__ on Python 2
            return 'approved, ' + str(self.approved) + ' article, ' + self.article

我已将此模型包含在admin.py中。管理员可以批准该文章,但是可以将pub_date设置为在管理员中批准文章的当前时间吗?

更新 根据Raja Simon的建议,这些模型适用于forms.py

class BlogForm(forms.ModelForm):
    class Meta:
        model = BlogModel
        fields = '__all__'
        # fields = ('id', 'title', 'article')

    def save(self, force_insert=False, force_update=False, commit=True):
        m = super(BlogForm, self).save(commit=False)
        # do custom stuff
        m.pub_date = timezone.now()
        if commit:
            m.save()
        return m

和admin.py

class BlogModelAdmin(admin.ModelAdmin):
    form = BlogForm
    fields = ('title', 'article', 'pub_date', 'submitted_date', 'author', 'approved')
    # fields = '__all__' won't work here, each field needs to be added individually as above
    pass
admin.site.register(BlogModel, BlogModelAdmin)

由于

2 个答案:

答案 0 :(得分:2)

您可以覆盖管理

中的表单保存
class BlogModelAdmin(admin.ModelAdmin):
    form = BlogModelForm
    pass
admin.site.register(BlogModel, BlogModelAdmin)

并在forms

class BlogModelForm(ModelForm):
    class Meta:
        model = BlogModel
        fields = '__all__'

    def save(self, force_insert=False, force_update=False, commit=True):
        m = super(BlogModelForm, self).save(commit=False)
        # do custom stuff
        m.pub_date = timezone.now()
        if commit:
            m.save()
        return m

答案 1 :(得分:1)

可以通过覆盖管理员中的save_model方法

def save_model(self, request, obj, form, change):
    if obj.approved:
        obj.pub_date =  timezone.now()

这可能优于覆盖模型本身的save方法。