Django multiple choices for an attribute model

Question:

I’ve got a model Post:

class Post(models.Model):
    # Each post can only have one author.
    author = models.ForeignKey(User, related_name='poster')
    INTRODUCTION = 'I'
    STORIES = 'S'
    CATEGORY_CHOICES = (
        (STORIES, 'Stories'),  # Variable name and display value
        (INTRODUCTION, 'Introduce Yourself'),
    )

    category = models.CharField(max_length=1,
                                choices=CATEGORY_CHOICES,
                                default=INTRODUCTION)

    #Add votes attribute in order to get a total reputation per user based on votes per post.
    votes = models.IntegerField(default=0)


    def __unicode__(self):
        return self.title

I have tried to create an instance of Post:

post = Post.objects.create(
        author = user,
        category = 'STORIES',
    )

but when I check the admin page it is not registered under the Stories category. Am I assigning the category wrongly?

Asked By: tryingtolearn

||

Answers:

You need to specify S (the first element of tuple; the actual value to be set in the model), not Stories (the second element of tuple; the human-readable name).

post = Post.objects.create(
    author=user,
    category='S'  # or Post.STORIES
)

See choices – Model field reference – Django documentation

Answered By: falsetru
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.