使用数据库中的数据填充选择

问题描述 投票:0回答:1

我需要用银行的数据填写一个选择。我有一个描述字段和一个类别字段,我需要 django 在打开注册表单时用类别填充选择。

我最近开始使用django,一直面临这个困难。有人在隧道尽头有一盏灯吗?

cadproduto.html


   <label for="exampleFormControlInput1">Categoria:</label>
                            <select class="form-control select" id="exampleFormControlSelect1">
                                {% for categoria in ListaDeCategorias %}
                                <option value="{{categoria.id}}">{{categoria.descricaocategoria}}</option>
                                {% endfor %}
                            </select>

表格.py

from django import forms
from .models import CadastroProduto

class ProdutoForm(forms.ModelForm):

    class Meta:
        model = CadastroProduto
        fields = ('descricaoresumida', 'precoprincipal', 'enviabalanca')

views.py

@login_required
def ListagemCategorias(request):
    ListaDeCategorias = models.CadastroCategoria.objects.all()
    return render(request, 'listagemcategorias.html', {'ListaDeCategorias': ListaDeCategorias})

django django-models django-views django-forms django-templates
1个回答
0
投票

如果你想在下拉列表中填充值,那么你需要使用

.values
查询方法从数据库表中获取值,这样你的查询就会像这样

@login_required
def ListagemCategorias(request):
    ListaDeCategorias = models.CadastroCategoria.objects.values("descricaocategoria")
    return render(request, 'listagemcategorias.html', {'ListaDeCategorias': ListaDeCategorias})
© www.soinside.com 2019 - 2024. All rights reserved.