如何限制django中的选择
How to limit the choice in django
我想创建一个只添加一个国家/地区团队的表格。
我想创建一个按钮 "Add team of Russia."
它需要一个国家/地区的有限形式的复选框。
models.py
RUSSIA = 'RUS'
USA = 'USA'
GERMANY = 'GER'
COUNTRY = (
(RUSSIA, "Russia"),
(USA, "USA"),
(GERMANY, "Germany"),
)
class Country(models.Model):
country = models.CharField(max_length=3, choices=COUNTRY, default=RUSSIA)
name_of_team = models.CharField(max_length=255, blank=True, null=True)
def __unicode__(self):
return self.name_of_team
forms.py
class AddCountryForm(forms.ModelForm):
class Meta:
model = Country
fields = ('country', 'name_of_team', )
你有两个选择:
- 您可以显示一个国家/地区的下拉菜单。
- 完全不能显示国家,保存对象前在视图中设置。
对于选项 1:
class AddCountryForm(forms.ModelForm):
country = forms.ChoiceField(choices=(('RUS', 'Russia'),))
class Meta:
model = Country
fields = ('name_of_team',)
对于选项 2:
class AddCountryForm(forms.ModelForm):
class Meta:
model = Country
fields ('name_of_team',)
def add_country(request):
form = AddCountryForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
obj.country = 'RUS'
obj.save()
return redirect('/thanks')
return render(request, 'form.html', {'form': form})
我想创建一个只添加一个国家/地区团队的表格。 我想创建一个按钮 "Add team of Russia." 它需要一个国家/地区的有限形式的复选框。
models.py
RUSSIA = 'RUS'
USA = 'USA'
GERMANY = 'GER'
COUNTRY = (
(RUSSIA, "Russia"),
(USA, "USA"),
(GERMANY, "Germany"),
)
class Country(models.Model):
country = models.CharField(max_length=3, choices=COUNTRY, default=RUSSIA)
name_of_team = models.CharField(max_length=255, blank=True, null=True)
def __unicode__(self):
return self.name_of_team
forms.py
class AddCountryForm(forms.ModelForm):
class Meta:
model = Country
fields = ('country', 'name_of_team', )
你有两个选择:
- 您可以显示一个国家/地区的下拉菜单。
- 完全不能显示国家,保存对象前在视图中设置。
对于选项 1:
class AddCountryForm(forms.ModelForm):
country = forms.ChoiceField(choices=(('RUS', 'Russia'),))
class Meta:
model = Country
fields = ('name_of_team',)
对于选项 2:
class AddCountryForm(forms.ModelForm):
class Meta:
model = Country
fields ('name_of_team',)
def add_country(request):
form = AddCountryForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
obj.country = 'RUS'
obj.save()
return redirect('/thanks')
return render(request, 'form.html', {'form': form})