I have a Gym Project in django, with booking_create (CreateView) to create bookings for a gym class. I am using a Model and Form, with user and class types. The HTML template has a Form for class booking. I want to make this Form unavailable when the class is full booked, showing instead a warning message.
My thoughts:
I should have a booking count for created bookings (e.g., booking_count), rest this value to the class capacity and save this in a variable (like, av_places= class_capacity-booking_count) and if av_places is greater than zero, show the Form for registration, otherwise show a warning message.
Not sure how to add this functionality to the class view
It is generally better to just count the number of existing bookings at the time the view is called.
You can handle this in the view in a couple different ways. One such way is to add an āavailableā flag to your context being rendered, where it is True if there is space available and False if not.
In the template, check that flag. If it is True, render the form. If it is False, render the error message.
Also, perform the same test in the post handling - you want to prevent the situation where two people are registering for the same spot at the same time. If the āavailableā flag has become false when the form is submitted, youāll want to render an error letting the user know that.
It makes much sense. I can get available bookings (for one of the classes _ā1ā) using class capacity minus existing bookings (Class_Book.objects.all().filter(āid_classā=1).count()). And according to the value, set the flag.
I know how to do it in Python but not in django. Iāam struggling with classviews of django. Should it be done with get_context_data? Make you suggest the syntaxis to add this funcionality to CreateView. I really appreciate since I have been looking to many examples trying to figure out how do it.
Following them through will help you understand the sequence of events, and give you some ideas on how to do this.
For this specific case:
Yes, thatās likely where I would do this. (Side note: If youāve got more than one place needing to do this, you could also create this test as a model method, and reference _that_in your template.)
See the example at Adding extra context
In your case, it might end up looking something like this:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['available'] = True if (capacity - bookings) else False
# Note: You do need to define or calculate "capacity" and "bookings"
return context