Home > Blockchain >  model form doesn't render form again when form is not valid
model form doesn't render form again when form is not valid

Time:01-15

I added Min and Max Value validators to my Django model and then when I enter a value out of this range, instead of rendering form again,it raises a value error.

ValueError: The view cars_form.views.rental_review didn't return an HttpResponse object. It returned None instead. [14/Jan/2023 21:44:50] "POST /cars_form/rental_review/ HTTP/1.1" 500 74599 It should be HTTP/1.1" 200

This is my Code models.py:

from django.db import models
from django.core.validators import MinValueValidator,MaxValueValidator
class Review(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])

forms.py :

from django import forms
from .models import Review
class ReviewForm(forms.ModelForm):
    class Meta:
        model = Review 
        fields = "__all__"

views.py:

from django.shortcuts import render,redirect
from django.urls import reverse
from .forms import ReviewForm
def rental_review(request):
    if request.method=='POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse('cars_form:thank_you')) # my template
    else:
        form = ReviewForm() # making an object
        return render(request,'cars_form/rental_review.html',context={'form':form})

if the form is not valid it must go on else statement but it doesn't and idk why.

CodePudding user response:

Try this,

def rental_review(request):
    if request.method=='POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse('cars_form:thank_you')) # my template
    else:
        form = ReviewForm() # making an object

    return render(request,'cars_form/rental_review.html',context{'form':form})

I have changed indentation of the last line

  • Related