0

我的 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", 选择 = it_const.TXN),

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

提前致谢。

4

2 回答 2

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 %}
于 2013-02-24T03:58:14.003 回答
-1

You can retrieve the database values in the view file, and then add them to an array, and then render the array as option for form field.

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.
于 2013-02-24T03:40:04.687 回答