django-在从数据库表自动生成的select语句中插入自定义选项 [英] django - insert a custom option in a select statement that is auto-generated from database table

查看:76
本文介绍了django-在从数据库表自动生成的select语句中插入自定义选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉(选择)表单,可将​​选择选项从数据库表中拉出.这些选项几乎总是在变化,具体取决于某些变量.

I have a drop down (select) form that pulls the select options form a database table. The options change almost all the time depending on certain variable.

我需要在下拉列表的底部添加一个选项,该选项将始终保持不变.会说更多选择"的东西.有任何想法吗?谢谢!

I need to add one more option all the way to the bottom of the drop down that will always be the same. Something that will say "more options". Any ideas? Thanks!

推荐答案

通过在正在使用的Form子类上覆盖 __ init __ 可以很容易地做到这一点.它在ModelForm上也应同样有效.我不确定您是如何根据问题来填充选择的.

This is easy enough to do by overriding __init__ on the Form sub-class you're using. It should work equally well on a ModelForm as well. I'm not sure how you're populating the choices based on the question though.

class ChoiceForm(Form):                                                         
    choice = ModelChoiceField(queryset=MyModel.objects.all())                    

    def __init__(self, *args, **kw):                                            
        super(ChoiceForm, self).__init__(*args, **kw)                           

        # Add to choices iterator                                               
        choice_field = self.fields['choice']                                    
        choice_field.choices = list(choice_field.choices) + [(0, 'More Options')]

当使用< p> 标签呈现时,将提供以下内容:

This gives the following when rendered with <p> tags:

<p>
    <label for="id_choice">Choice:</label> 
    <select name="choice" id="id_choice">
        <option value="" selected="selected">---------</option>
        <option value="0">More Options</option>
    </select>
</p>

不过请注意,此字段选择在创建后将被固定.如果传递给您的查询集的结果发生变化,则普通的ModelChoiceField将自动更新其选择.

Be warned though, this fields choices will be fixed after you create it. A normal ModelChoiceField will auto-update its choices if the results of the queryset you passed it would be changed.

这篇关于django-在从数据库表自动生成的select语句中插入自定义选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆