开发者

ModelChoiceField labels are incorrect

开发者 https://www.devze.com 2023-03-11 14:26 出处:网络
Not sure how to update the labels on a ModelChoiceField Model: class Category(models.Model): categoryText = models.CharField(max_length=50)

Not sure how to update the labels on a ModelChoiceField

Model:

class Category(models.Model):

    categoryText = models.CharField(max_length=50)
    parentCat = models.ForeignKey('self',null=True,blank=True)

Form:

class CategoryForm(forms.Form):
    category  = forms.ModelChoiceField(queryset=Category.objects.all())

Righ开发者_Python百科t now when I display the form, I get "Category Object" as the lable of the drop down. I like to change the lables to what is stored in categoryText.

How do I do this?


class Category(models.Model):
    categoryText = models.CharField(max_length=50)
    parentCat = models.ForeignKey('self',null=True,blank=True)

    def __unicode__(self):
        return self.categoryText

The unicode method is used internally by Django when it want's to print a human-friendly version of the particular model object/table row (in the admin, or as a form label for example). You should write a unicode method for every model you create.

Here is django's entry about the unicode function

0

精彩评论

暂无评论...
验证码 换一张
取 消