Displaying a specific field in a django form

 ̄綄美尐妖づ 提交于 2019-12-24 10:21:51

问题


I have the following field in a django form:

position = forms.ModelChoiceField(Position.objects.order_by('-ordering'),
                                    empty_label='Select Position',)

In my Position model, I am using the unicode field to display the field called "position". However, in this particular form, I want the output to be a different field in the model called "position-select". How would I do this without altering the default output of the unicode field?

Thank you.


回答1:


Try "subclassing ModelChoiceField and override label_from_instance", per the example at https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield. You could specify a reference to the __unicode__ function of your other field within that overridden class.




回答2:


This is what worked:

class PositionSelect(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.select_display

class Position(forms.Form):
    position = PositionSelect(Position.objects.order_by('-ordering'),
                                    empty_label='Select Position',)


来源:https://stackoverflow.com/questions/7629323/displaying-a-specific-field-in-a-django-form

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