我正在使用保存到数据库的选项,保存时它会显示['option1','option2'],我只需要显示正确的名称即可。 我需要我的模型继续作为models.CharField
models.py
PETN_CHOICES = (
('Cachorro','Cachorro'), ('Gato','Gato'), ('Pássaros', 'Pássaros'), ('Peixes','Peixes'), ('Reptéis','Reptéis'), ('Roedores','Roedores')
)
class Negocio(models.Model):
pet_aceitos = models.CharField(max_length=255, choices=PETN_CHOICES)
forms.py
PETN_CHOICES = (
('Cachorro','Cachorro'), ('Gato','Gato'), ('Pássaros', 'Pássaros'), ('Peixes','Peixes'), ('Reptéis','Reptéis'), ('Roedores','Roedores')
)
class NegocioForm(UserCreationForm):
pet_aceitos = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple, choices=PETN_CHOICES, )
答案 0 :(得分:0)
您使用的表单字段和模型字段之间有很大的差异。在Negocio
模型中,pet_aceitos仅接受一个值与新实例一起存储,其中在NegocioForm
中,您将强制选择多项字段,即值列表。您想做的可能是:
在models.py
中:
PETN_CHOICES = (
('Cachorro','Cachorro'), ('Gato','Gato'), ('Pássaros', 'Pássaros'), ('Peixes','Peixes'), ('Reptéis','Reptéis'), ('Roedores','Roedores')
)
class Negocio(models.Model):
pet_aceitos = models.CharField(max_length=255, choices=PETN_CHOICES)
在views.py
中:
class NegocioForm(ModelForm):
class Meta:
model = Negocio
fields = ('pet_aceitos',)
class NegocioView(FormView):
form_class = NegocioForm
template_name = "yourtemplate.html"
success_url = "success_redirect_url_name"
在您的yourtemplate.html
中:
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send message">
</form>