我正在運行一個 django 應用程式并嘗試使用用戶將在前端 html 端提交的 django 表單創建物件的實體。我最后得到的錯誤似乎與類別屬性相對應
這就是我的 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")
這是課堂形式的樣子
class Listing_Form(forms.ModelForm):
class Meta:
model = Listing
fields = "__all__"
這是我的views.py函式
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()
當視圖函式中的那一行出現時
print(form.errors)
它給了我以下錯誤
ul li category ul li 選擇一個有效的選項。7 不是可用的選擇之一。”
uj5u.com熱心網友回復:
您的 ChoiceField 定義中的問題是您int對元組的 0 索引使用了錯誤的型別 ( )。
categories = ((1,"Clothing/Footwear"), (2,"Books"), (3,"Electronics"), (4,"Cosmetics"), (5,"Toys"), (6,"Home/Garden"), (7,"Sport/Leisure"))
正如您在此鏈接中看到的,他們也使用 astring作為該索引。所以在這個鏈接中是這樣的:
GEEKS_CHOICES =(
("1", "One"),
("2", "Two"),
("3", "Three"),
("4", "Four"),
("5", "Five"),
)
在您的情況下,它應該如下所示:
categories = (("1","Clothing/Footwear"), ("2","Books"), ("3","Electronics"), ("4","Cosmetics"), ("5","Toys"), ("6","Home/Garden"), ("7","Sport/Leisure"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513593.html
