I have created an appointment booking system however i want to avoid any past dates being booked before it reaches create booking object which is then saved to the database.
Here is my views.py
class BookingView(View):
def get(self, request, *args, **kwargs):
return render(request, "availability.html")
def post(self, request, *args, **kwargs):
form = AvailabilityForm(request.POST)
if form.is_valid():
data = form. cleaned_data
bookingList = Appointment.objects.filter(start__lt=data['end_time'], end__gt=data['start_time'])
if not bookingList:
booking = Appointment.objects.create(
name=data["name"],
email=data["email"],
start=data["start_time"],
end=data["end_time"]
)
booking.save()
return render(request, "success.html", {
"booking":booking
},)
else:
name = data["name"]
return render(request, "booked.html",{
"name":name,
},)
CodePudding user response:
You can add an extra validation to the date fields like this:
from django.utils import timezone
class AvailabilityForm(forms.Form):
# ... the fields
def clean_start_time(self)
start = self.cleaned_data.get('start_time')
if start < timezone.now():
raise forms.ValidationError('the date must be after now.')
return data
Can se more at https://docs.djangoproject.com/en/4.0/ref/forms/validation/#cleaning-a-specific-field-attribute
Next, you need little rewrite your view and send the form to the template in order to display these errors, like explained in this docs:
