我是Django 4.1的初学者。我正在使用model来编辑表单并将其呈现在网页中。运行正常。当我点击submit时,我的函数识别POST方法,但从不验证表单。我确信我必须修复我的模型或表单中的一个bug,但我不知道在哪里。
中models.py
class Auction(models.Model):
HOUSE = "HOU"
MOTORS = "MOT"
PROPERTY = "PPT"
HOBBIES = "HOB"
INFORMATION_TECHNOLOGY = "IT"
MUSIC = "MUS"
BOOK = "BOK"
CATEGORY_CHOICES = [
(HOUSE, "All for your House"),
(MOTORS, "Car, Moto, Boat"),
(PROPERTY, "Houses, flats, manors"),
(HOBBIES, "Hobbies"),
(INFORMATION_TECHNOLOGY, "Laptop, Desktop, Mobile Phone"),
(MUSIC, "CD, Musical Intrusments"),
(BOOK, "Books, Comics,...")
]
ONE = 1
THREE = 3
SEVEN = 7
FOURTEEN = 14
DURATION_CHOICES = [
(ONE, "1 day"),
(THREE, "3 days"),
(SEVEN, "7 days"),
(FOURTEEN, "14 days")
]
title = models.CharField(max_length=64)
description = models.TextField(max_length=500, blank=True)
creation_date = models.DateTimeField(auto_now_add=True)
image = models.URLField(null=True, blank=True, default="")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller")
duration = models.CharField(max_length=7, choices=DURATION_CHOICES, default=SEVEN)
category = models.CharField(max_length=3, choices=CATEGORY_CHOICES, default=INFORMATION_TECHNOLOGY)
price = models.DecimalField(max_digits=12, decimal_places=2, default=0.0)
def __str__(self):
return f"{self.id}: {self.title}"
中forms.py
class CreateListingsForm(forms.ModelForm):
class Meta:
model = Auction
fields = ["title", "description", "image", "category", "duration", "price"]
以及www.example.com中views.py
def create(request):
if request.method == "POST":
form = CreateListingsForm(request.POST)
form.instance.user = request.user
form.instance.creation_date = datetime.now()
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "auctions/listings.html", {
"form": form
})
else:
form = CreateListingsForm()
return render(request, "auctions/listings.html", {
"form": form
})
我试过像下面这样处理示例。我也试过在我的表单中覆盖init。
编辑:我做了print(form.error)
,结果是<ul class="errorlist"><li>duration<ul class="errorlist"><li>Select a valid choice. 7 is not one of the available choices.</li></ul></li></ul>
。问题可能是我的默认值?
编辑2:
错误是字段的类型,因此当我将其更改为'IntegerField'时,它仍然有效
3条答案
按热度按时间vbkedwbf1#
我认为您的字段列表([“标题”、“描述”、“图片”、“类别”、“持续时间”、“价格”])中没有用户和创建日期,因此您的表单仍然无效。
试试看:
dphi5xsq2#
你可以试试这个:
uurv41yg3#
max_length
和min_length
:如果提供了这些参数,则这些参数可确保字符串最多或至少为给定长度。我不认为您正在检查int的最大值是否小于或等于7,所以这就是验证失败的原因。您需要更改这一点,可能需要在表单中添加验证规则,或者将
CharField
更改为数字字段。