我遍历Block对象列表,使用将block_type链接到ModelForm模型的映射字典为每个对象实例化ModelForm,然后将表单附加到我传递给模板以供显示的列表中。
for block in blocks:
block_instance = block_map[block.block_type].objects.get(id=block.id)
new_form = block_forms[block.block_type]
new_form_instance = new_form(
request.user,
request.POST or None,
instance=block_instance,
prefix = block.id
)
form_zones.append(new_form_instance)
稍后,在检查request.POST时我会验证每个表单
if request.POST.get("save_submit"):
for zone_form_check in story_zones:
for block_form_check in zone_form_check:
if block_form_check.is_valid():
print(block_form_check.cleaned_data.get("content"))
saved = block_form_check.save()
print(saved.content)
valid = True
if valid:
return redirect("Editorial:content", content_id=content_id)
cleaning_data.get(“content”)生成更新的数据,但即使在有效表单上调用save()之后,saved.content也会生成对象的旧内容属性。换句话说,一个有效的表单正在调用save(),但它没有保存。
有问题的表格之一(目前我唯一的表格)是:
class Edit_Text_Block_Form(ModelForm):
content = forms.CharField(widget = forms.Textarea(
attrs = {
"class": "full_tinymce"
}),
label = "",
)
class Meta:
model = TextBlock
fields = []
def __init__(self, user, *args, **kwargs):
self.user = user
super(Edit_Text_Block_Form, self).__init__(*args, **kwargs)
有问题的模型是一个TextBlock,它继承自Block objets。这两个都在下面:
class Block(models.Model):
zone = models.ForeignKey(Zone)
order = models.IntegerField()
weight = models.IntegerField()
block_type = models.CharField(max_length=32, blank=True)
class Meta:
ordering = ['order']
def delete(self, *args, **kwargs):
# Calling custom delete methods of child blocks
child = block_map[self.block_type].objects.get(id=self.id)
if getattr(child, "custom_delete", None):
child.custom_delete()
# Overriding delete to check if there are any other blocks in the zone.
# If not, the zone itself is deleted
zones = Block.objects.filter(zone=self.zone).count()
if zones <= 1:
self.zone.delete()
# Children of Block Object
class TextBlock(Block):
content = models.TextField(blank=True)
为什么调用saved = block_form_check.save()的任何想法都没有更新我的模型?
谢谢!
答案 0 :(得分:1)
我认为这是因为您通过在表单的Meta类中设置fields = []
来有效地从表单中排除所有模型字段。这意味着Django不再将表单上手动定义的content
字段与模型中的字段相关联。
相反,请将字段设置为['content']
,它应该按预期工作。
答案 1 :(得分:-1)
TL; DR表单名称不能以html4 specs
的数字开头尝试使用prefix =&#34; block_%s&#34; %block.id