我想创建一个表单,我只会添加一个国家/地区的团队。 我想创建一个按钮“添加俄罗斯队”。 它需要一个有限形式的一个国家的复选框。
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', )
答案 0 :(得分:1)
您有两种选择:
对于选项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})