本文介绍了如何强制 - 保存“空”/不变的django管理内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的一个管理模型中有一些内联,它们的默认值在添加新的实例时,可能不需要更改。不幸的是,django将不会将这些内联识别为新对象,除非某些值已更改。这迫使我添加内联,更改任意值,保存,更改值并再次保存以达到所需的效果。



唯一的解决方案到目前为止,添加一个隐藏的改变字段,当添加一个新的内联时,它将通过java脚本填充。因为这感觉非常黑客,我希望有一个更优雅的解决方案。



任何想法都将不胜感激。



谢谢Daniel,

解决方案

我花了很多时间弄清楚,但实际上很简单。从django.contrib导入$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

$ b $ (ModelForm):
def has_changed(self):
如果数据与初始值不同,应返回True
始终返回true即使不变内嵌也将被验证和保存。
返回True

class CheckerInline(admin.StackedInline):
检查内联的基类
extra = 0
form = AlwaysChangedModelForm


I have some inlines in one of my admin models which have default values which likely won't need to be changed when adding a new instance with "Add another ...". Unfortunately django won't recognize these inline as new objects unless some value has changed. This forces me to add an inline, change an arbitrary value, save, change the value back and save again to reach the desired effect.

The only solution i've come up with so far is to add a hidden 'changed'-field wich would be populated via java-script when adding a new inline. As this feels very hackish i hope there is a more elegant solution.

Any ideas would be greatly appreciated.

Thanks, Daniel.

解决方案

It took me quite some time to figure out but it is actually really simple.

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管理内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 04:12