More than basic form validation with Django [duplicate]
I'm learning Django with a small app allowing people to book houses for lodging. I have two models, describing a house and a booking (I'm currently working without a "Customer" model):
# models.py
from django.db import models
class Housing(models.Model):
name = models.CharField(max_length=255)
capacity = models.SmallIntegerField()
class Booking(models.Model):
house = models.ForeignKey(Housing, on_delete=models.CASCADE)
arrival_date = models.DateField(auto_now_add=False)
departure_date = models.DateField(auto_now_add=False)
client_id = models.TextField()
nb_travellers = models.SmallIntegerField()
I also have a ModelForm matching the Booking model, in which a customer can book a house:
# forms.py
from django.forms import ModelForm
from .models import Booking
class BookingForm(ModelForm):
"""Form to make a booking"""
class Meta:
model = Booking
fields = "__all__"
In my view, I retrieve the form data, and I'd like to add some validation before adding the new booking instance to the database:
- arrival_date must be before departure_date
- The number of travellers must not be higher then the houe capacity
- There must not be an existing booking in the databse which has overlapping dates with the new booking
I already have code to compute those, it works in additional testing scripts I made, but I am struggling to integrate it properly in the view. Should I look deeper in Django forms validation documentation ? I read something about a clean
method to write directly into the ModelForm class, but I am a bit lost ... Someone got any tip or suited tutorial ?
from django.shortcuts import render
from .forms import BookingForm
def booking_form(request):
if request.method == 'POST':
form = BookingForm(request.POST)
if form.is_valid():
form.save()
else:
form = BookingForm()
return render(request, 'home.html', {'form': form})