[英]How to make a select field using Django model forms (using set values)?
I recently switched from using simple forms in Django to model forms. I am now trying to use a select field in my form that has set field names (eg:Europe,North America,South America...) I thought I would just add a select input type to the for fields but it shows up as just a regular text input.我最近从 Django 中使用简单的 forms 切换到 model forms。我现在尝试在我的表单中使用 select 字段,该字段已设置字段名称(例如:欧洲、北美、南美...)我想我会添加for 字段的 select 输入类型,但它显示为只是常规文本输入。 The select field is supposed to be "continent".
select 字段应该是“大陆”。 Does anyone know how to to d this??
有谁知道如何做到这一点?
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.
Here you can use ModelChoiceField provided by django forms. Define a Country model containing all the countries, and use that as a QuerySet here.这里可以使用django forms提供的ModelChoiceField,定义一个包含所有国家的Country model,在这里作为QuerySet使用。 It will be also be dynamic that can be changed later.
它也将是动态的,以后可以更改。
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'})
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.