[Answered ]-Pass data from template to view in Django

2πŸ‘

βœ…

Please don’t suggest to pass info using url. It can lead to manipulation very easily.

Sadly, every other way to pass the information to the view is not that much better or more secure.

Never ever trust user input.

No matter what way you choose in the end, you will have to validate the input.

And using URLs has some advantages. For example: You can send a link to the route you just found to a friend (so called deep link). Otherwise your friend would have to click through your form by himself.


If you are still interested in doing this by URL you could do it as follows:

You could change your url schema for the URL that you called book:seats to contain all of the required information. Assume that book:seat looks like the following in your urls.py:

url(r'^book/seats/$', views.seats, name='book:seats')

You chould change this URL pattern to contain all of the information you want to pass to the seats view:

url(r'^book/seats/(?P<bus_number>\w+)/(?P<route>\w+)/(?P<date>\w+)/(?P<time>\w+)$', views.seats, name='book:seats')

This would add a so called named group to your URL pattern. You can read about named groups here: named groups documentation. Obviously, you will have to modify this example URL pattern to fit your needs.

Next step is to update your view function to handle all those extra view arguments:

def seats(request, bus_number, route, date, time):
    template = 'seats.html'
    context = {}
    return render(request, template, context)

The last step is to modify the way you render the link in your template:

<a href="{% url 'book:seats' info.bus_number info.route info.date info.time %}">Book</a>

You have to add the arguments in the same order as they are used in the seats function. You can read more about this in the official documentation here: template tag documentation.

πŸ‘€Jens

Leave a comment