简体   繁体   中英

Django CharField w/Choices, model instance needed

Need to turn a CharField into a forms.ChoiceField in the admin.

The choices come from external API based on a model instance param. Since I need the model instance, I put the code in a ModelForm.__init__() method. This does not turn the CharField into a ChoiceField :

class OfferAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(OfferAdminForm, self).__init__(*args, **kwargs)
        if hasattr(self, 'instance'):
            CHOICES = (
                ('A', 'Choice A'),
                ('B', 'Choice B'),
            )
            category_id = forms.ChoiceField(choices = CHOICES)

Putting the CHOICES and category_id assignment outside of __init__() works fine. I think I'm hitting some sort of race condition, but not sure how to go about fixing it.

我一点都不了解您要在这里做什么,但是您需要将字段分配给字段字典。

self.fields["category_id"] = forms.ChoiceField(choices = CHOICES)

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