I made a Django form. If the user tries to submit the form when entering wrong data then error is showed in the form and it is not submitted but when the user enters correct data and submit the form it gets submitted. The problem is that when the user presses the back button, he can still see that error in the form. The error message still stays. What can I do about it?
The below screenshots will help you understand my problem.
In the above image I have entered the number of rooms as 0.
As expected, I got an error.
So I changed the number of rooms to 1.
Now when I pressed the 'search availability' button I got the desired page.
The problem arises if I press the browser back button. As you can see the error is still shown in the form.
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields = ['check_in_date', 'check_in_time', 'check_out_time',
'person', 'no_of_rooms']
widgets = {
'check_in_date': FutureDateInput(),
'check_in_time': TimeInput(),
'check_out_time': TimeInput(),
}
"""Function to ensure that booking is done for future and check out is after check in"""
def clean(self):
cleaned_data = super().clean()
normal_book_date = cleaned_data.get("check_in_date")
normal_check_in = cleaned_data.get("check_in_time")
normal_check_out_time = cleaned_data.get("check_out_time")
str_check_in = str(normal_check_in)
format = '%H:%M:%S'
try:
datetime.datetime.strptime(str_check_in, format).time()
except Exception:
raise ValidationError(
_('Wrong time entered.'),
code='Wrong time entered.',
)
# now is the date and time on which the user is booking.
now = timezone.now()
if (normal_book_date < now.date() or
(normal_book_date == now.date() and
normal_check_in < now.time())):
raise ValidationError(
"You can only book for future.", code='only book for future'
)
if normal_check_out_time <= normal_check_in:
raise ValidationError(
"Check out should be after check in.", code='check out after check in'
)
models.py
class Booking(models.Model):
customer_name = models.CharField(max_length=30)
check_in_date = models.DateField()
check_in_time = models.TimeField()
check_out_time = models.TimeField()
room_number = models.CharField(validators=[validate_comma_separated_integer_list], max_length=9)
ROOM_CATEGORIES = (
('Regular', 'Regular'),
('Executive', 'Executive'),
('Deluxe', 'Deluxe'),
('King', 'King'),
('Queen', 'Queen'),
)
category = models.CharField(max_length=9, choices=ROOM_CATEGORIES)
PERSON = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
)
person = models.PositiveSmallIntegerField(choices=PERSON, default=1)
no_of_rooms = models.PositiveSmallIntegerField(
validators=[MaxValueValidator(1000), MinValueValidator(1)], default=1
)
views.py
def booking(request):
if request.method == 'POST':
form = BookingForm(request.POST)
if form.is_valid():
print(request.POST)
request.session['normal_book_date'] = request.POST['check_in_date']
request.session['normal_check_in'] = request.POST['check_in_time']
request.session['normal_check_out'] = request.POST['check_out_time']
request.session['normal_person'] = int(request.POST['person'])
request.session['normal_no_of_rooms_required'] = int(
request.POST['no_of_rooms']
)
print(request.session['normal_check_in'])
response = search_availability(request.session['normal_book_date'],
request.session['normal_check_in'],
request.session['normal_check_out'],
request.session['normal_person'],
request.session['normal_no_of_rooms_required'])
if response:
context = {
'categories': response,
'username': request.user.username
}
return render(request, 'categories.html', context)
return HttpResponse("Not Available")
else:
context = {
'form': form,
'username': request.user.username
}
return render(request, 'book.html', context)
context = {
'form': BookingForm(),
'username': request.user.username
}
return render(request, 'book.html', context)
GitHub repo link https://github.com/AnshulGupta22/room_slot_booking
CodePudding user response:
The problem is not your code, but browser's cache/history mechanism.
That content of page is served from the previous load, it does not make a new request. You can easily confirm this looking at the terminal/logs of the runserver
command.
CodePudding user response:
Try add else condution: (Im not shure about that)
else:
context = {
'form': BookingForm(),
'username': request.user.username
}
return render(request, 'book.html', context)