Search code examples
pythondjangoadmin

while submitting post from admin it gives me something like this Select a valid choice is not one of the available choices


I am trying to give posts category choices , everything works fine but if I add posts from admin panel I get error something like this

Select a valid choice. SSC is not one of the available choices.

this is my Posts/models.py

from django.db import models
from django.core.validators import FileExtensionValidator
# Create your models here.


CATEGORIES = (
        ('SSC', 'SSCQUESTION'),
        ('CAT', 'CATQUESTION'),
    )


class Category(models.Model):
    title = models.CharField(max_length = 120, verbose_name="Title" )
    updated_at = models.DateTimeField(auto_now_add=True, verbose_name="Updated at")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"
        ordering = ['title']
    def __str__(self):
        return self.title



class Posts(models.Model):
    title = models.CharField(max_length=60)
    file_upload = models.FileField(null= True, blank=True, validators=[FileExtensionValidator(['pdf'])])
    content = models.TextField()
    category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE,choices = CATEGORIES)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    
    # class Meta:
    #     verbose_name = "Post"
    #     verbose_name_plural = "Posts"
    #     ordering = ['-created_at']


    def __unicode__(self):
        return self.title 

    def __str__(self):
        return self.title
    

In admin panel this gives error like this

post-error


Solution

  • remove choices

    category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE)
    

    Go to the Category table in the admin panel and create some categories there.. Those categories will now be populated in the dropdown in the Post creation page