Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - collecting data from a HTML <select>

I've seen a couple of documents on how to collect the data from a HTML statement in Django but none of them were very clear to me. Does anybody have a real working example to share?

In my case I have something like this in my template file:

<select title="my_options">
   <option value="1">Select value 1</option>
   <option value="2">Select value 2</option>
</select>

What goes in the views.py in order to collect the selected value? Thank you!

like image 873
avatar Avatar asked Jan 24 '11 20:01

avatar


People also ask

How can I get form data in Django?

Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.

What is linebreaks in Django?

{{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to <p> tags.


1 Answers

If it's a GET request, request.GET['my_options']. If it's a POST, then request.POST['my_options']. This will be a string, either "1" or "2" (or "<script>alert('I hacked you!')</script>")

Either way, it's probably better to use the Django forms framework to save you the hassle of writing the HTML, and sanitizing the returned values.

like image 162
Thomas Avatar answered Oct 23 '22 04:10

Thomas