gpt4 book ai didi

python - Django:如何根据表单的非持久字段自定义保存模型/表单?

转载 作者:行者123 更新时间:2023-12-01 04:53:25 25 4
gpt4 key购买 nike

自从我在上一篇文章中问过二合一问题以来,我重新发布了这个问题。

我想将 Entry 模型中的字段 publication_date 设置为在设置 bool 值 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}}

谢谢。

最佳答案

重写EntryAdminsave_model()方法:

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() 方法:

class EntryAdminForm(forms.ModelForm):
....
def save(self, *args, **kwargs):
entry = super(EntryAdminForm, self).save(*args, **kwargs)
if self.cleaned_data.get('to_publish'):
entry.publication_date = datetime.now()
if kwargs.get('commit', True):
entry.save()
return entry

关于python - Django:如何根据表单的非持久字段自定义保存模型/表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27984602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com