下拉菜单html代码,包含来自django的选项

时间:2013-02-24 03:19:34

标签: html django drop-down-menu

我的HTML代码如下:

<select name="txn" tabindex="3" id="txn" class="fixed" onfocus="highlightInput(this.id)" onblur="unhighlightInput(this.id)">
    <option value="RR" my="{{txn|genselected:"RR"|safe}>RR</option>
    <option value="CR" my="{{txn|genselected:"CR"|safe}}">CR</option>
    <option value="SR" my="{{txn|genselected:"SR"|safe}}">SR</option>
    <option value="OR" my="{{txn|genselected:"OR"|safe}}">OR</option>
</select>

txn在forms.py中定义为:

txn = forms.ChoiceField(label =“txn”,choices = it_const.TXN),

我的问题: 选项值是否在数据库中动态增加?我想从数据库中读取选项值并将它们放在html的下拉菜单中。你能帮我解决HTML代码以及如何从txn表单字段中读取选项并在菜单选项中显示它。

提前致谢。

2 个答案:

答案 0 :(得分:0)

视图

def view_name(request):
    form = OptionForm()
    options = Option.objects.filter()
    return render(request, 'page.html', {
        'form': form, 
        'options': options,
    })

HTML

<form method="post">
    {% csrf_token %}    
    {{form}}
    <input type="submit" value="Submit">
</form>

{% for option in options %}
<p>{{option.field}}</p>
{% endfor %}

答案 1 :(得分:-1)

您可以在视图文件中检索数据库值,然后将它们添加到数组中,然后将该数组呈现为表单字段的选项。

TXN_choices = Options.objects.all()

#and then run a for loop to dynamically generate the options array:
TXN = (
        ('x', 'xxx'),
        ('y', 'yyyy'),
    )

and then render the ModelForm.