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 valuepath/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.
Answer
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:
forms.py
urls.py
Example of valid URL matching the report_details
pattern: /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:
views.py
The view Report
is responsible just for validating the user input and redirecting the user to the view that will
actually process the report, which is ReportDetails
.
The form is posted to Report
. Report
validates the input and if it is valid, it fires a redirect towards the
ReportDetails
. ReportDetails
grab the date information from the URL, process the querysets and finally returns
to the user, rendering the template.
report.html
report_details.html
The final result would be something like this:
Filtering with the proper URL:
Caveats
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:
urls.py
views.py
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: /report/?date=2017-03-17&status=pending
.
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.