简体   繁体   中英

How do I filter the choices in a ModelForm that has a CharField with the choices attribute (and hence a Select Field)

I understand I am able to filter queryset of Foreignkey or Many2ManyFields, however, how do I do that for a simple CharField that is a Select Widget (Select Tag).

For example:

PRODUCT_STATUS = (
                  ("unapproved", "Unapproved"),
                  ("approved", "Listed"),
                  #("Backorder","Backorder"),
                  #("oos","Out of Stock"),
                  #("preorder","Preorder"),
                  ("userdisabled", "User Disabled"),
                  ("disapproved", "Disapproved by admin"),
                  )

and the Field:

o_status = models.CharField(max_length=100, choices=PRODUCT_STATUS, verbose_name="Product Status", default="approved")

Suppose I wish to limit it to just "approved" and "userdisabled" instead showing the full array (which is what I want to show in the admin), how do I do it?

Thanks!

class YourModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        self.fields['your_field'].choices = (('a', 'A'), ('b', 'B'))

    class Meta:
        model = YourModel

I guess this ain't too different from overriding a queryset from a ForeignKey or M2M attribute.

PS: Thanks peritus from #django at irc.freenode.net

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