Home > Net >  Django model form will not validate due to this error
Django model form will not validate due to this error

Time:10-06

im running a django app and trying to create an instance of an object using a django form that the user will submit on the frontend html side. the error i get at the end seems to correspond with the category attribute

this is what the class model looks like in my models.py

class Listing(models.Model):
    title = models.CharField(max_length=64)
    description = models.TextField()
    image = models.ImageField(blank=True)
    categories = ((1,"Clothing/Footwear"), (2,"Books"), (3,"Electronics"), (4,"Cosmetics"), (5,"Toys"), (6,"Home/Garden"), (7,"Sport/Leisure"))
    category = models.CharField(choices=categories, max_length=2)
    starting_price = models.DecimalField(decimal_places=2, max_digits=10)
    lister = models.ForeignKey(User, on_delete=models.CASCADE, related_name="selling")

here is what the class form looks like

class Listing_Form(forms.ModelForm):
    class Meta:
        model = Listing
        fields = "__all__"

here is my views.py function

def create(request):
    if request.method == "POST":
        form = Listing_Form(request.POST)
        print(form.errors)
        if form.is_valid():
            print('valid')
            form.save()
            return HttpResponseRedirect(reverse("index"))
        else:
            print('invalid')
    else:
        form = Listing_Form()

when that line in the views function occurs

print(form.errors)

it gives me the following error

ul li category ul li Select a valid choice. 7 is not one of the available choices."

CodePudding user response:

The issue in your ChoiceField definition is that you use the wrong type (int) for the 0-index of the tuple.

categories = ((1,"Clothing/Footwear"), (2,"Books"), (3,"Electronics"), (4,"Cosmetics"), (5,"Toys"), (6,"Home/Garden"), (7,"Sport/Leisure"))

As you can see in this link, they use a string for this index as well. So in this link it is like this:

GEEKS_CHOICES =(
    ("1", "One"),
    ("2", "Two"),
    ("3", "Three"),
    ("4", "Four"),
    ("5", "Five"),
)

In your case it should look like this:

categories = (("1","Clothing/Footwear"), ("2","Books"), ("3","Electronics"), ("4","Cosmetics"), ("5","Toys"), ("6","Home/Garden"), ("7","Sport/Leisure"))
  • Related