I am trying to capture the POST request data for each field and store it in the session so that I can use the data in another view. But I am getting errors in the other view because the session variables are returning 'None'.
Before, I had written the code using a non-class based view and fetched the values with request.POST.get('name')
and this worked. What should I be doing here?
class TripsView(FormView):
""" A view to show all trips and receive trip search data """
template_name = "products/trips.html"
form_class = SearchTripsForm
def form_valid(self, form):
"""
Takes the POST data from the SearchTripsForm and stores it in the session
"""
trip_choice = form.cleaned_data["destination"].id
self.request.session["destination_choice"] = trip_choice
self.request.session["searched_date"] = "26-12-2021"
self.request.session["passenger_total"] = form.cleaned_data[
"passengers"
]
return super(TripsView, self).form_valid(form)
def get_context_data(self, **kwargs):
""" Adds to the context the Product objects categorized as trips """
context = super().get_context_data(**kwargs)
context["destinations"] = Product.objects.filter(category=3)
return context
def get_success_url(self):
""" Overides the success url when the view is run """
return reverse("selection")
My other view is as follows:
class SelectTripView(View):
"""
Provides the user a set of choice options based on their search input in
products.TripsView
"""
template_name = "bookings/trips_available.html"
form_class = DateChoiceForm
def get(self, request):
"""
Initialises the DateChoiceForm with data from SearchTripsForm
& render to the template
"""
searched_date = self.request.session["searched_date"]
print(searched_date)
naive_searched_date = datetime.strptime(searched_date, "%Y-%m-%d")
gte_dates = self.trips_matched_or_post_date(searched_date)
lt_dates = self.trips_preceding_date(searched_date)
... etc etc...
The code flags an error here at the datetime.strptime()
method because it says argument 1 must be a string not a tuple - (None)
Update:* I have located that the problem is because the date string is being converted to a tuple (2,0,2,1 etc..) - maybe because it includes punctuation dashes '-' between Y-M-D? Is there a workaround for this? That being said, the string was just a placeholder. In the real case, I am pulling the value from form data which gives me date object and would need to be serialized before sending to the session.
I am confused as to why using request.POST.get() to retrieve the form data in non classed based View did not encounter such errors. Is there a difference to the data once it is cleaned_data?