Django Admin not saving pre-populated inline fields which are left in their initial state(Django Admin 未保存处于初始状态的预填充内联字段)
问题描述
我有一些自定义管理代码初始化一些内联子对象.
I have some custom admin code which initialises some inline child objects.
如果用户编辑内联子对象的默认值之一,则在保存父对象时创建该子元素.
If the user edits one of the inline child object's default values, then that child element is created when the parent object is saved.
我假设 Django 正在检查值是否已从它们的 initial
值更改,并且仅在用户更改值时才保存.
I assume that Django is checking whether values have changed from their initial
values and only saving if the user has changed a value.
是这样吗?
如果用户选择不更改默认值,我如何强制 Django Admin 创建具有未更改默认值的内联子对象?
How do I force Django Admin to create inline child objects with their unchanged default values, if the user chooses not to change the default values?
class PrepopIpInlineFormSet(forms.models.BaseInlineFormSet):
model = Ip
def __init__(self, *args, **kwargs):
super(PrepopIpInlineFormSet, self).__init__(*args, **kwargs)
initial = # calculate a set of default Ip model initial values
self.initial = initial
class PrepopIpInline(admin.options.InlineModelAdmin):
template = "admin/linked.html"
model = Ip
formset = PrepopIpInlineFormSet
fk_name = 'sim'
admin_model_path = None
show_url = True
def __init__(self, *args):
super(PrepopIpInline, self).__init__(*args)
if self.admin_model_path is None:
self.admin_model_path = self.model.__name__.lower()
def get_formset(self, request, obj=None, **kwargs):
formset = super(PrepopIpInline, self).get_formset(request, obj, **kwargs)
formset.request = request
return formset
def get_extra(self, request, obj=None, **kwargs):
if obj:
return 0
else:
return ApnGgsn.objects.all().count()
推荐答案
来源:如何强制保存空"/未更改的 django admin inline?
from django.contrib import admin
from django.forms.models import BaseInlineFormSet, ModelForm
class AlwaysChangedModelForm(ModelForm):
def has_changed(self):
""" Should returns True if data differs from initial.
By always returning true even unchanged inlines will get validated and saved."""
return True
class CheckerInline(admin.StackedInline):
""" Base class for checker inlines """
extra = 0
form = AlwaysChangedModelForm
这篇关于Django Admin 未保存处于初始状态的预填充内联字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django Admin 未保存处于初始状态的预填充内联字段
基础教程推荐
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01