Django admin:如何在ModelAdmin中迭代表单属性

时间:2018-02-13 10:06:41

标签: python django django-admin

我使用Django 1.11.10和python 3.6;我需要在admin中迭代form个值。怎么做?

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)

2 个答案:

答案 0 :(得分:0)

迭代form对象的属性与迭代任何其他python对象的属性相同。使用dir()。见here

答案 1 :(得分:0)

不清楚为什么要在clean方法中设置表单上的属性:

class ServerForm(forms.ModelForm):

    class Meta:
        model = Server

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

如果您在表单的实例上设置属性,那么您不必在save_model方法中执行此操作:

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