1

I use Django 1.11.10 and python 3.6; I need to iterate form values in admin. How to do that?

class ServerForm(forms.ModelForm):

    class Meta:
        model = Server

    def clean(self):
        setattr(self, 'field1', 'value1')
        setattr(self, 'field2', 'value2')



class ServerAdmin(admin.ModelAdmin):
    form = ServerForm

    def save_model(self, request, obj, form, change):

        # this works
        # but how to iterate form?

        obj.field1 = form.field1
        obj.field2 = form.field2

        # AttributeError: 'ServerForm' object has no attribute 'items'
        for key, value in form.items():
            setattr(obj, key, value)

        super(ServerAdmin, self).save_model(request, obj, form, change)
sirjay
  • 1,767
  • 3
  • 32
  • 52

2 Answers2

0

Iterating through attributes of a form object would be the same as iterating through the attributes of any other python object. Use dir(). See here

0

It's not clear why you are setting attributes on the form in the clean method:

class ServerForm(forms.ModelForm):

    class Meta:
        model = Server

    def clean(self):
        setattr(self, 'field1', 'value1')
        setattr(self, 'field2', 'value2')

If you set the attributes on the form's instance, then you won't have to do it in the save_model method:

def clean(self):
    setattr(self.instance, 'field1', 'value1')
    setattr(self.instance, 'field2', 'value2')
Alasdair
  • 298,606
  • 55
  • 578
  • 516