Django:如何基于表单的非持久字段自定义保存模型/表单?

时间:2015-01-16 13:04:52

标签: python django django-models django-forms

我正在重新发布这个问题,因为我在上一篇文章中提到了2合1。

我想在Entry模型中设置字段 publication_date ,以便在设置布尔 to_publish 时进行更改为true,类似于模型中的自定义save()方法,但我无法在表单上执行此操作。

#blog/models.py
class Entry(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    slug = models.SlugField(max_length=100, unique=True)
    creation_date = models.DateTimeField(editable=False)
    publication_date = models.DateTimeField(editable=False, null=True)
    modification_date = models.DateTimeField(editable=False)

    author = models.ForeignKey(User)
    categories = models.ManyToManyField(Category)
    tags = models.ManyToManyField(Tag)

    objects = EntryQuerySet.as_manager()

    def __str__(self):
        return self.title

    def was_published_recently(self):
        now = datetime.datetime.now()
        return now - datetime.timedelta(days=1) <= self.publication_date <= now

    def is_published(self):
        return self.publication_date is not False

    is_published.boolean = True
    is_published.short_description = 'Is it Published?'

    def get_absolute_url(self):
        return reverse("entry_detail", kwargs={"slug": self.slug})

    class Meta():
        verbose_name = "Blog Entry"
        verbose_name_plural = "Blog Entries"
        ordering = ['-creation_date']

    def save(self, *args, **kwargs):
        """ On save, update timestamps """
        if not self.id:
            self.creation_date = datetime.datetime.now()
        self.modification_date = datetime.datetime.now()
        return super(Entry, self).save(*args, **kwargs)

#blog/forms.py
class EntryAdminForm(forms.ModelForm):
    to_publish = forms.BooleanField(required=False)

    class Meta:
        model = Entry
        fields = ['title', 'body', 'slug', 'author', 'categories', 'tags']

#blog/admin.py
class EntryAdmin(MarkdownModelAdmin):
    form = EntryAdminForm
    list_display = ("title", "author", "creation_date", "publication_date", "is_published")
    prepopulated_fields = {"slug": ("title",)}
    formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}}

谢谢。

1 个答案:

答案 0 :(得分:2)

覆盖save_model()的{​​{1}}方法:

EntryAdmin

另一个(也是更复杂的)选项是覆盖class EntryAdmin(MarkdownModelAdmin): ... def save_model(self, request, obj, form, change): if form.cleaned_data.get('to_publish'): obj.publication_date = datetime.now() obj.save() 方法:

EntryAdminForm.save()