How to get the label of a choice in a Django forms ChoiceField?

╄→гoц情女王★ 提交于 2019-12-18 10:08:20

问题


I have a ChoiceField, now how do I get the "label" when I need it?

class ContactForm(forms.Form):
     reason = forms.ChoiceField(choices=[("feature", "A feature"),
                                         ("order", "An order")],
                                widget=forms.RadioSelect)

form.cleaned_data["reason"] would only give me "feature" or "order" or so.


回答1:


This may help:

reason = form.cleaned_data['reason']
reason = dict(form.fields['reason'].choices)[reason]



回答2:


See the docs on Model.get_FOO_display(). So, should be something like :

ContactForm.get_reason_display()

In a template, use like this:

{{ OBJNAME.get_FIELDNAME_display }}



回答3:


This the easiest way to do this: Model instance reference: Model.get_FOO_display()

You can use this function which will return the display name: ObjectName.get_FieldName_display()

Replace ObjectName with your class name and FieldName with the field of which you need to fetch the display name of.




回答4:


If the form instance is bound, you can use

chosen_label = form.instance.get_FOO_display()



回答5:


Here is a way I came up with. There may be an easier way. I tested it using python manage.py shell:

>>> cf = ContactForm({'reason': 'feature'})
>>> cf.is_valid()
True
>>> cf.fields['reason'].choices
[('feature', 'A feature')]
>>> for val in cf.fields['reason'].choices:
...     if val[0] == cf.cleaned_data['reason']:
...             print val[1]
...             break
...
A feature

Note: This probably isn't very Pythonic, but it demonstrates where the data you need can be found.




回答6:


You can have your form like this:

#forms.py
CHOICES = [('feature', "A feature"), (order", "An order")]
class ContactForm(forms.Form):
     reason = forms.ChoiceField(choices=CHOICES,
                                widget=forms.RadioSelect)

Then this would give you what you want:

reason = dict(CHOICES)[form.cleaned_data["reason"]]



回答7:


I think maybe @webjunkie is right.

If you're reading from the form from a POST then you would do

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            contact = form.save()
            contact.reason = form.cleaned_data['reason']
            contact.save()



回答8:


Im using @Andrés Torres Marroquín way, and I want share my implementation.

GOOD_CATEGORY_CHOICES = (
    ('paper', 'this is paper'),
    ('glass', 'this is glass'),
    ...
)

class Good(models.Model):
    ...
    good_category = models.CharField(max_length=255, null=True, blank=False)
    ....

class GoodForm(ModelForm):
    class Meta:
        model = Good
        ...

    good_category = forms.ChoiceField(required=True, choices=GOOD_CATEGORY_CHOICES)
    ...


    def clean_good_category(self):
        value = self.cleaned_data.get('good_category')

        return dict(self.fields['good_category'].choices)[value]

And the result is this is paper instead of paper. Hope this help



来源:https://stackoverflow.com/questions/761698/how-to-get-the-label-of-a-choice-in-a-django-forms-choicefield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!