通过列表传递选择

时间:2019-03-31 23:40:52

标签: django django-models django-forms

我正在使用保存到数据库的选项,保存时它会显示['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, )

1 个答案:

答案 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>