is_valid()不适用于我的Django表单

mzmfm0qo  于 2022-11-18  发布在  Go
关注(0)|答案(3)|浏览(128)

我是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'时,它仍然有效

vbkedwbf

vbkedwbf1#

我认为您的字段列表([“标题”、“描述”、“图片”、“类别”、“持续时间”、“价格”])中没有用户和创建日期,因此您的表单仍然无效。
试试看:

def create(request):
    if request.method == "POST":
        form = CreateListingsForm(request.POST)
        if form.is_valid():
            listing = form.save(commit=false)
            listing.user_id = request.user.pk
            listing.create_date = datetime.now()
            listing.save()
            return HttpResponseRedirect(reverse("index"))
        else: # I think this else block is not so necessary
            return render(request, "auctions/listings.html", {
            "form": form
            })
    else:
        form = CreateListingsForm()
        return render(request, "auctions/listings.html", {
        "form": form
        })
dphi5xsq

dphi5xsq2#

你可以试试这个:

def create(request):
    if request.method == "POST":
        form = CreateListingsForm(request.POST)
        if form.is_valid():
           form.instance.user = request.user
           form.instance.creation_date = datetime.now()
           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
        })
uurv41yg

uurv41yg3#

duration = models.CharField(max_length=7, choices=DURATION_CHOICES, default=SEVEN)

max_lengthmin_length:如果提供了这些参数,则这些参数可确保字符串最多或至少为给定长度。
我不认为您正在检查int的最大值是否小于或等于7,所以这就是验证失败的原因。您需要更改这一点,可能需要在表单中添加验证规则,或者将CharField更改为数字字段。

相关问题