i'm a beginner with Django 4.1. I'm using model to edit a form and render it in a webpage. This run correctly. When i click on submit, my function recognize the POST method but never validate the form. I'm sure that i have to fix a bug in my models or my form but i don't know where.
in 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}"
in forms.py
class CreateListingsForm(forms.ModelForm):
class Meta:
model = Auction
fields = ["title", "description", "image", "category", "duration", "price"]
and in 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
})
I've tried to handle instance like below. I've tried to override init in my form too.
Edit:
i've do print(form.error)
and the result is <ul ><li>duration<ul ><li>Select a valid choice. 7 is not one of the available choices.</li></ul></li></ul>
. May the problem is my default value?
Edit2:
the error was the type of the field so it works when i'm changed it to `IntegerField
CodePudding user response:
Can you post an example of what your submitting in your form?
EDIT
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.
CodePudding user response:
I think you haven't 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
})
Please for English