Devon Moore asks:
I want to have the user specify a date in a custom form. This date will append the current URL with the date value
path/YYYY-MM-DD/I then need to capture the date and use it to filter data from the database to display that date’s data.
I’m using class based views and for the report I’m using generic view since this view is a custom report I’m building using multiple db models.
Here is what Devon wants to achieve:
There are a couple of ways to achieve the desired result. Using class-based views, we could perhaps do something like this:
Example of valid URL matching the
/report/2017-03-17/. If you want to change the URL to
use slashes instead of dashes (
/report/2017/03/17/), change the URL pattern to this:
Report is responsible just for validating the user input and redirecting the user to the view that will
actually process the report, which is
The form is posted to
Report validates the input and if it is valid, it fires a redirect towards the
ReportDetails grab the date information from the URL, process the querysets and finally returns
to the user, rendering the template.
The final result would be something like this:
Filtering with the proper URL:
This implementation will only work if you only need the date to filter the report.
If you need to pass extra information to do the filtering of the querysets, I would recommend sending the form data
directly to the
Report view. And perhaps even using a GET request, because you are not modifying the data.
Something like this:
Then you would end up having a URL like this:
/report/?date=2017-03-17. And if you had more information in the form,
like the status, it would append in the URL:
The URL would still be friendly, and the implementation would be simpler.
Get the Code
The code is available on GitHub: github.com/sibtc/askvitor.