简体   繁体   中英

Django ModelForm not detecting field

I have the following models:

class Model1(models.Model):
     field1 = ...
     field2 = ...
     class Meta:
          abstract = True

class Model2(models.Model):
     field3 = ...
     field4 = ...
     class Meta:
          abstract = True

I have concrete implementations of the above:

class ConcreteModel1(Model1):
     field1_group = ... # foreign key to ConcreteModel3


class ConcreteModel2(Model2):
     field3_test = ... # foreign key to ConcreteModel4

I have abstract ModelForms:

 class Model1Form(ModelForm):
         class Meta:
          widgets = { ... }
          abstract = True

 class Model2Form(ModelForm):
         class Meta:
          widgets = { ... }
          abstract = True

I have concrete ModelForms:

 class ConcreteModel1Form(Model1Form):
         class Meta(Model1Form.Meta):
             model = ConcreteModel1
             exclude = ('field1_group')


 class ConcreteModel2Form(Model2Form):
         class Meta(Model2Form.Meta):
             model = ConcreteModel2
             exclude = ('field3_test')

Now as you can see there are parallels between the two model forms. The problem is that in my template field1 is visible for ConcreteModel1Form (expected behavior) But in another template field3 is not visible for ConcreteModel2Form (unexpected behavior).

If I comment out exclude=('field3_test') then field3 is visible in the template (expected behavior) but form validation fails since field3_test is None and is a required field.

What am I missing? This seems to be a problem with my code that i can't figure out. This behavior is clearly inconsistent and I am not able to see the difference in my code.

Any ideas how to debug this? What could be the problem?

I tried removing abstract=True from the base form class, does not help.

Explicitly specifying the field list in the ConcreteModelForm classes works though. But I don't see why exclude list works on one case but not the other.

Could you try adding a trailing comma in your exclude field list. Let us know the result.

exclude = ('field1_group', )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM