3

I am trying to create a custom django admin field that is not apart of the model. I am having to mark it as read only or else I get an FieldError saying Unknown field(s) (yaml_data) specified for Setting. Check fields/fieldsets/exclude attributes of class SettingAdmin.

I have read and followed the guide django admin - add custom form fields that are not part of the model but still seem to be having issues.

If I comment out the readonly I get the error above, but I really want to be able to modify it here and save it.

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))
Jared Mackey
  • 3,998
  • 4
  • 31
  • 50
  • It looks like the yaml field is just the `value` field represented slightly differently. You might want to consider updating the `value` field on clean – karthikr Mar 14 '16 at 15:03
  • It is, but I just want an editable area that is for yaml, not JSON. It is stored in the backend as JSON, but is read by humans and even the API as YAML. – Jared Mackey Mar 14 '16 at 15:05
  • right. What i meant was, you are hiding the json field, and showing the yaml field. And on submit, in the clean method, just set the json field using the content of the yaml field. You should be all set – karthikr Mar 14 '16 at 15:06
  • Ok, how would I populate it with YAML data on load instead of JSON data? – Jared Mackey Mar 14 '16 at 15:07

0 Answers0