Как убрать сообщения об ошибках при успешной отправке формы в Django?

Я создал форму на Django. Если пользователь пытается отправить форму при вводе неправильных данных, то в форме появляется ошибка и она не отправляется, но когда пользователь вводит правильные данные и отправляет форму, она отправляется. Проблема в том, что когда пользователь нажимает кнопку назад, он все еще видит ошибку в форме. Сообщение об ошибке все еще остается. Что я могу с этим сделать?

Нижеприведенные скриншоты помогут вам понять мою проблему.

enter image description here

На изображении выше я ввел количество комнат как 0.

enter image description here

Как и ожидалось, я получил ошибку.

enter image description here

Поэтому я изменил количество комнат на 1.

enter image description here

Теперь, когда я нажал кнопку "доступность поиска", я получил нужную страницу.

enter image description here

Проблема возникает, если я нажимаю кнопку "Назад" в браузере. Как вы можете видеть, ошибка все еще отображается в форме.

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 https://github.com/AnshulGupta22/room_slot_booking

Проблема не в вашем коде, а в механизме кэша/истории браузера.

Такое содержимое страницы обслуживается из предыдущей загрузки, оно не делает новый запрос. Вы можете легко подтвердить это, посмотрев на терминал/логи команды runserver.

Попробуйте добавить еще одно предостережение: (я не уверен в этом)

else:
    context = {
        'form': BookingForm(),
        'username': request.user.username
        }
    return render(request, 'book.html', context)
Вернуться на верх