Django Admin 未保存处于初始状态的预填充内联字段

Django Admin not saving pre-populated inline fields which are left in their initial state(Django Admin 未保存处于初始状态的预填充内联字段)

本文介绍了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 未保存处于初始状态的预填充内联字段

基础教程推荐