如何获取 Django 表单 ChoiceField 中选项的标签?

发布于 2024-07-17 05:02:04 字数 421 浏览 4 评论 0原文

我有一个 ChoiceField,现在如何在需要时获取标签

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

form.cleaned_data["reason"] 只给我 featureorder values 左右。

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"] only gives me the feature or order values or so.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

友欢 2024-07-24 05:02:04

请参阅 Model.get_FOO_display( )。 所以,应该是这样的:

ContactForm.get_reason_display()

在模板中,使用如下:

{{ OBJNAME.get_FIELDNAME_display }}

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 }}
倾城月光淡如水﹏ 2024-07-24 05:02:04

这可能会有所帮助:

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

This may help:

reason = form.cleaned_data['reason']
reason = dict(form.fields['reason'].choices)[reason]
我爱人 2024-07-24 05:02:04

这是最简单的方法: 模型实例引用:Model.get_FOO_display()

您可以使用此函数返回显示名称:ObjectName.get_FieldName_display()

ObjectName 替换为您的类名和 FieldName 以及您需要获取其显示名称的字段。

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.

我是男神闪亮亮 2024-07-24 05:02:04

如果表单实例已绑定,则可以使用

chosen_label = form.instance.get_FOO_display()

If the form instance is bound, you can use

chosen_label = form.instance.get_FOO_display()
路还长,别太狂 2024-07-24 05:02:04

这是我想出的一个方法。 可能有更简单的方法。 我使用 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

注意:这可能不是很 Pythonic,但它演示了在哪里可以找到您需要的数据。

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.

尤怨 2024-07-24 05:02:04

好的。 我知道这是非常的旧帖子,但阅读它对我帮助很大。 我想我有一些补充。

这里问题的关键在于模型方法。

ObjectName.get_FieldName_display()

不适用于表单。

如果您有一个不基于模型的表单,并且该表单有一个选择字段,那么如何获取给定选择的显示值。

这是一些可能对您有帮助的代码。

您可以使用此代码从已发布的表单中获取选择字段的显示值。

display_of_choice = dict(dateform.fields['fieldnane'].choices)[int(request.POST.get('fieldname'))]

“int”的存在是基于选择的选择是一个整数。 如果选择索引是字符串,那么您只需删除 int(...)

OK. I know this is very old post, but reading it helped me a lot. And I think I have something to add.

The crux of the matter here is that the the model method.

ObjectName.get_FieldName_display()

does not work for forms.

If you have a form, that is not based on a model and that form has a choice field, how do you get the display value of a given choice.

Here is some code that might help you.

You can use this code to get the display value of a choice field from a posted form.

display_of_choice = dict(dateform.fields['fieldnane'].choices)[int(request.POST.get('fieldname'))]

the 'int' is there on the basis the choice selection was a integer. If the choice index was a string then you just remove the int(...)

夏尔 2024-07-24 05:02:04

你可以有这样的表格:

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

然后这会给你你想要的:

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

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"]]
猫七 2024-07-24 05:02:04

我使用@Andrés Torres Marroquín 方式,我想分享我的实现。

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]

结果是这是纸而不是
希望这有帮助

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

擦肩而过的背影 2024-07-24 05:02:04

确认阿迪和保罗的反应最适合形式而不是模型。 将 Ardi 推广到任何参数:

    class AnyForm(forms.Form):
        def get_field_name_display(self, field_name):
            return dict(self.fields[field_name].choices[self.cleaned_data[field_name]]

或者将此方法放在一个单独的类中,然后在表单中将其子类化

class ChoiceFieldDisplayMixin:
    def get_field_name_display(self, field_name):
        return dict(self.fields[field_name].choices[self.cleaned_data[field_name]]


class AnyCustomForm(forms.Form, ChoiceFieldDisplayMixin):
    choice_field_form = forms.ChoiceField(choices=[...])

现在为任何选择字段调用相同的方法:

form_instance = AnyCustomForm()
form_instance.is_valid()
form_instance.get_field_name_display('choice_field_form')

confirm that Ardi's and Paul's response are best for forms and not models. Generalizing Ardi's to any parameter:

    class AnyForm(forms.Form):
        def get_field_name_display(self, field_name):
            return dict(self.fields[field_name].choices[self.cleaned_data[field_name]]

Or put this method in a separate class, and sub-class it in your form

class ChoiceFieldDisplayMixin:
    def get_field_name_display(self, field_name):
        return dict(self.fields[field_name].choices[self.cleaned_data[field_name]]


class AnyCustomForm(forms.Form, ChoiceFieldDisplayMixin):
    choice_field_form = forms.ChoiceField(choices=[...])

Now call the same method for any Choice Field:

form_instance = AnyCustomForm()
form_instance.is_valid()
form_instance.get_field_name_display('choice_field_form')
旧时浪漫 2024-07-24 05:02:04

我认为也许@webjunkie 是对的。

如果您正在阅读 POST 中的表单,那么您会这样做

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()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文