[Fixed]-Django populate the admin fields list after checking a condition

1👍

You should use ModelAdmin‘s get_fields method. You don’t need to use get_object_or_404 to get association as it is already linked with current object passed to get_fields method.

class LabelAdmin(admin.ModelAdmin):
    def get_fields(self, request, obj=None):
        if obj is None:
            return super(LabelAdmin, self).get_fields(request, obj)
        fields = self.fields or list()
        fields = list(fields)    # to make copy of original list
        for x in xrange(1, 6):
            fields.remove('short_text{}'.format(x))
        if obj.assosiative.short_text1 == 1:
            fields.append('short_text1')
        if obj.assosiative.short_text2 == 1:
            fields.append('short_text2')
        if obj.assosiative.short_text3 == 1:
            fields.append('short_text3')
        if obj.assosiative.short_text4 == 1:
            fields.append('short_text4')
        if obj.assosiative.short_text5 == 1:
            fields.append('short_text5')
        return fields    
    class Meta:
        model = Label

Leave a comment