自定义django管理员字段不在模型上

时间:2016-03-14 14:53:18

标签: python django django-admin yaml

我正在尝试创建一个不属于模型的自定义django管理字段。我不得不将其标记为只读,否则我会FieldErrorUnknown field(s) (yaml_data) specified for Setting. Check fields/fieldsets/exclude attributes of class SettingAdmin.

我已阅读并遵循指南https://github.com/Yalantis/uCrop,但似乎仍有问题。

如果我注释掉readonly我得到上面的错误,但我真的希望能够在这里修改并保存它。

admin.py

class SettingForm(forms.ModelForm):
    yaml_data = forms.Textarea()

    def save(self, commit=True):
        yaml_data = self.cleaned_data.get('yaml_data', None)
        if yaml_data:
            self.instance.yaml_data = yaml_data
        super(SettingForm, self).save(commit=commit)

    class Meta:
        model = Setting
        # exclude = ('value',)
        fields = '__all__'


class SettingAdmin(admin.ModelAdmin):
    form = SettingForm
    readonly_fields = ('yaml_data',)

    # fields = ('name', 'server', 'default', 'yaml_data')

    fieldsets = (
        (None,
         {
             'fields': ('name', 'server', 'default', 'value', 'yaml_data'),
         }),
    )

site.register(Setting, SettingAdmin)

models.py

class Setting(models.Model):
    name = models.CharField(max_length=250, null=False, blank=False)
    value = JSONField(blank=False, null=False)
    server = models.ForeignKey('Server', null=True, blank=True)
    default = models.BooleanField(default=False)

    @property
    def yaml_data(self):
        if type(self.value) in [list, dict, tuple]:
            return yaml.safe_dump(self.value, default_flow_style=False)
        return str(self.value)

    @yaml_data.setter
    def yaml_data(self, value):
        self.value = json.dumps(yaml.safe_load_all(value))

0 个答案:

没有答案