My question involves passing variables from the template to view in Django.
I know of passing variables in the URL and through a form. The problem I have with the first one is that the url could be manipulated which is not what I want. Is there anyway to prevent that?
Right now this is what I have as a band-aid:
<form action="/match/" method="post">
{% csrf_token %}
<input type="hidden" name="name1" value="{{ male_results }}">
<input type="hidden" name="userid1" value="{{ male_pic_userid }}">
<input type="hidden" name="name2" value="{{ female_results }}">
<input type="hidden" name="userid2" value="{{ female_pic_userid }}">
<input type="submit" value="Submit" />
</form>
Is there a way to avoid having to use this? Thank you!
There's an option called 'Templates' with another option to 'Toggle context' and you can see all the variables passed to your template, as well as the ability to see the code behind the template. Save this answer.
uid is the variable that you want to pass to the view.
render_to_string() loads a template like get_template() and calls its render() method immediately. It takes the following arguments. The name of the template to load and render. If it's a list of template names, Django uses select_template() instead of get_template() to find the template.
There are broadly 3 ways to hold onto this kind of information:
Just stuff the data you want into the request.session
dictionary; it'll persist per-user, and you can access it easily:
# view1
request.session['name1'] = male_results
request.session['userid1'] = male_pic_userid
# view2 (or elsewhere in view1)
male_results = request.session.get('name1')
male_pic_userid = request.session.get('userid1')
POST
, page content is dictated by the URL and session data — URLs are no longer unique, and users can't share a particular page that relies on session infoSomething like /match/?name1=foo1&userid1&name2=bar&userid2=2
. You can either add these manually (<a href='/match/?name1={{ male_results }}...
) or by changing your POST
form to GET
.
POST
data to every navigation action is a huge pain.There are three ways to get data from an html page into the server backend: URL (GET), Form (POST), and Cookies.
Any of the three may be manipulated so you need to validate everything on the server every time no matter what.
In terms of efficiency, per your post title, URL (GET) variables a slightly more efficient since form data goes through a mild amount of encoding before it is sent on to the server.
Under normal usage the standard is to use URL (GET) variables when you are retrieving data from the server and to use Form (POST) variables when you want to manipulate (edit/delete) data on the server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With