Note that there are some explanatory texts on larger screens.

plurals
  1. POdjango form validation with parameters from view
    text
    copied!<p>I have a problem with my form validation in Django.</p> <p>Let's say I have 2 apartments with option for booking them. User should choose start_date and end_date when he books apartment. When I'm validating my form for booking I check few conditions and one of them is to see if there are booked days between start and end date. If there is then the error is raised. It was working fine for one apartment in database. It looked like this:</p> <pre><code>class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['booking_start', 'booking_end', 'gsm'] def clean(self): cleaned_data = self.cleaned_data form_booking_start = cleaned_data.get("booking_start") form_booking_end = cleaned_data.get("booking_end") the_apartment = Apartman.objects.get(id=2) between = Booking.objects.filter(booking_start__gte=form_booking_start, booking_end__lte=form_booking_end).exists() if form_booking_start and form_booking_end: ... if between: raise forms.ValidationError("It seems like there are days that are already booked between your booking start and booking end. Please take care of it and book days that are not already booked.") return cleaned_data </code></pre> <p>But the problem is that when I add another apartment error is raised every time if user book dates which are already booked for some other apartment. So I need to check id of that apartment and then just check if the booking is related to that apartment. So if my apartment id=2 then it should be like this:</p> <pre><code>between = Booking.objects.filter(booking_start__gte=form_booking_start, booking_end__lte=form_booking_end, apartman__id=2).exists() </code></pre> <p>Problem is, I don't know how to pass value of that id from view to my form. My view looks something like this:</p> <pre><code>def booking(request, apartman_id): a = Apartman.objects.get(id=apartman_id) if request.method == 'POST': f = BookingForm(request.POST) if f.is_valid(): .... else: f = BookingForm() </code></pre> <p>So, finally, how can I pass value of that apartman_id to my form?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload