创建选择字段时出错

时间:2018-07-11 14:24:03

标签: mysql django

我正在创建选择字段,但未在模板上显示我的下拉列表:

我的模特:

Inactive = 0
Active = 1

state_choices = (
    (Inactive, 'Inactive'),
    (Active, 'Active')
)
class Tipe(models.Model):

    name = models.CharField(max_length=50)
    details = models.CharField(max_length=100)
    state = models.CharField(
        max_length=1,
        choices=state_choices,
        default=Active,
    )

class People(models.Model):

    name=models.CharField(max_length=100)
    phone=models.CharField(max_length=9, null=True)
    state = models.CharField(
        max_length=1,
        choices=state_choices,
        default=Active,
    )
    tipe = models.ForeignKey(Tipe, on_delete=models.CASCADE, null=True)

forms.py:

class PeopleForm(forms.Form):

    name = forms.CharField(max_length=100)
    name.widget.attrs.update({'class':'form-control', 'required': 'true' })


    phone = forms.CharField(max_length=9)
    phone.widget.attrs.update({'class':'form-control', 'minlength':'9'})

    optionState = (('1', 'Active'),('0', 'Inactive'),)
    state = forms.ChoiceField(choices=optionState )
    state.widget.attrs.update({'class':'form-control', 'required':'true'})

    tipe = forms.ModelChoiceField(queryset=Tipe.objects.filter(state=1), widget=forms.Select)

这会在我的模板上返回:

<select id="id_tipe" name="tipe">
<option value="" selected="selected">---------</option>
<option value="1">Tipe object</option>
<option value="3">Tipe object</option>
</select>

不要在下拉菜单中显示值,仅显示Tipe对象的tipes模型名称。请任何建议..谢谢!!

1 个答案:

答案 0 :(得分:0)

您从未指定过如何打印Tipe对象的方式,因此Python / Django会使用此类模型的默认字符串表示形式。通常是'Tipe model (123)'123对象的主键。

通过覆盖__str__函数,您可以定义一种自定义的方式来呈现对象。例如,您可以使用.name属性,例如:

class Tipe(models.Model):

    name = models.CharField(max_length=50)
    details = models.CharField(max_length=100)
    state = models.CharField(
        max_length=1,
        choices=state_choices,
        default=Active,
    )

    def __str__(self):
        return self.name

您当然可以定义一些更复杂的内容,关键是您可以定义一种方法来表示下拉菜单中的对象以及在模板中显示对象的其他实例。

尽管这与问题无关,但我建议您将IntegerField用于state字段,因为0是整数,而不是字符(或字符串),因此更接近用于表示状态的值的类型。