如何使用Django模型表单(使用设置值)创建一个选择字段?

sqougxex  于 2023-05-01  发布在  Go
关注(0)|答案(2)|浏览(177)

我最近从使用Django中的简单表单切换到模型表单。我现在尝试在我的表单中使用一个已设置字段名称的选择字段(例如:欧洲、北美、南美)。..)我以为我只会在for字段中添加一个选择输入类型,但它显示为只是一个常规的文本输入。选择字段应该是“大陆”。有人知道怎么做吗??

class TripForm(forms.ModelForm):
    # city = forms.TextInput()
    # country = forms.TimeField()
    # description = forms.Textarea()
    # photo = forms.ImageField()
    class Meta:
        model = Trip
        fields = ('city', 'country', 'continent', 'description', 'photo')

        widget = {
            'city': forms.TextInput(attrs={'class': 'form-control'}),
            'country': forms.TextInput(attrs ={'class': 'form-control'}),
            'continent': forms.SelectMultiple(attrs= {'class':'form-control'}),
            'description': forms.TextInput(attrs = {'class': 'form-control'}),
            # 'photo': forms.ImageField(attrs = {'class': 'form-control'}),
        }

[![enter image description here][1]][1]

This is the form continent should show as a select.
pcrecxhr

pcrecxhr1#

在这里你可以使用django表单提供的ModelChoiceField。定义一个包含所有国家/地区的Country模型,并在此处将其用作QuerySet。它也将是动态的,可以稍后更改。

from django import forms
from .models import Trip, Country

class TripForm(forms.ModelForm):
    class Meta:
        model = Trip
        fields = ['name', 'country', 'start_date', 'end_date']

    
    country = forms.ModelChoiceField(
        queryset=Country.objects.all(),
        to_field_name='name',
        required=True,  
        widget=forms.Select(attrs={'class': 'form-control'})
    )
3htmauhk

3htmauhk2#

我也有类似的问题,我就这样解决了。对不起,如果字段是意大利语

forms.pyclass FormCapitaliBilancio(forms.ModelForm):

class Meta:
    model = CapitoliRiscossione
    fields = [  
                'ruolo',
                'entrata',
                'capitolo',
                'accertamento',
                'tipo'
            ]
entrata = forms.ModelChoiceField(
    queryset=DecodEquitaliaCodEntrata.objects.all().exclude(tassa = ' ').values('tassa').distinct().order_by('tassa'),
    to_field_name='tassa',
    required=True,  
    widget=forms.Select(attrs={'class': 'form-control'})
)

模板

<div class="form-group row">
                        <label class="col-sm-2 col-form-label">Entrata</label>
                        <div class="col-sm-10" onchange="verificaEntrata()">
                          <select class="js-example-basic-single col-sm-12" name="{{ form_user.entrata.name }}" id="{{ form_user.entrata.id_for_label }}">
                            {% for value, label in form_user.fields.entrata.choices %}
                            <option value="{{ value.tassa }}"{% if value.tassa == instance.entrata %} selected{% endif %}>{{ value.tassa }}</option>
                        {% endfor %}
                          </select>
                        </div>
                      </div>

views.py

def capitaliContabilitaAggiorna(request,id_capitalolo):abilitazione = SoggettoMenu.objects.filter(utente_menu_id=请求。user,menu_princ_id=6)

if abilitazione:

    instance = get_object_or_404(CapitoliRiscossione, id=id_capitolo)
    
    elenco_entrate = DecodEquitaliaCodEntrata.objects.all().exclude(tassa = ' ').values('tassa').distinct().order_by('tassa')

    if request.method == "POST":

        form_sogg = FormCapitoliBilancio(request.POST, instance=instance)

        if form_sogg.is_valid():

            print(form_sogg.cleaned_data['entrata']['tassa'])

            form = form_sogg.save(commit=False)

            form.entrata = form_sogg.cleaned_data['entrata']['tassa']

            form.utente = request.user

            form.save()                

            return HttpResponseRedirect(reverse('capitoli_contabilita'))

    form_user = FormCapitoliBilancio(instance=instance)

    context = { 'form_user':form_user, 
                'instance':instance,
                'elenco_entrate':elenco_entrate
            }

    return render(request, "riscossione_coattiva/contabilita_capitoli_aggiorna.html", context)

相关问题