ModelMultipleChoiceField

ModelMultipleChoiceField

本文介绍了Django ModelMultipleChoiceField和CheckboxSelectMultiple-显示来自queryset的额外数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以访问除Django形式ModelMultipleChoiceField中的键,值对之外的其他数据?

Is it possible to access additional data apart from key, value pairs in django forms ModelMultipleChoiceField?

我的目标是生成一个具有其名称的输入(复选框)(值)和其他信息(例如价格,其他描述以及可能的其他数据)。

My goal is to generate an input (checkbox) with its name (value) and extra information like price, additional description and possibly other data.

我使用django-crispy-forms,我希望通过创建模板将其保留在其中例如,

I use django-crispy-forms and I would love to keep it within it by creating a template for example.

编辑

我在想类似的东西

<input value="{{ object.id }}"> 
{{object.name}} - {{object.description}} {{object.price}}


推荐答案

是的,有一种方法称为 label_from_instance 的方法可以接受 obj 作为参数并返回 obj 表示形式。

Yes there is a way its a method called label_from_instance which accept obj as arguments and return the obj representation.

您可以从ModelMultipleChoiceField继承并覆盖它,或在表单创建过程中动态更改它。下面是一些示例:

You can either Inherit from ModelMultipleChoiceField and override it, or dynamically change it during form creation. Here are some examples:

from django.forms import ModelMultipleChoiceField

class MyModelMultipleChoiceField(ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id

#and then you have to use it in your form:
class MyForm(forms.ModelForm):
    my_multi_choice_field = MyModelMultipleChoiceField(queryset=...)



或通过覆盖



or by overriding

class MyForm(forms.ModelForm):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['my_multi_choice_field'].label_from_instance = self.label_from_instance

这篇关于Django ModelMultipleChoiceField和CheckboxSelectMultiple-显示来自queryset的额外数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 11:03