[Answered ]-Is_valid() method not work with my form in Django

1👍

I think you don’t have "user" and "creation_date" in your fields list (["title", "description", "image", "category", "duration", "price"]), so your form will be still invalid.

Try this:

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
        })
👤ckabah

0👍

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

max_length and min_length: if provided, these arguments ensure that the string is at most or at least the given length.

I don’t think you are checking if int has max value less than or equal to 7 so that’s what is failing your validation. You will need to change that and perhaps add a validation rule in your form or change from CharField to a numeric field.

0👍

Simply you can try this:

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
        })

Leave a comment