I have the following django template (http://IP/admin/start/ is assigned to a hypothetical view called view):
{% for source in sources %} <tr> <td>{{ source }}</td> <td> <form action="/admin/start/" method="post"> {% csrf_token %} <input type="hidden" name="{{ source.title }}"> <input type="submit" value="Start" class="btn btn-primary"> </form> </td> </tr> {% endfor %}
sources
is the objects.all()
of a Django model being referenced in the view. Whenever a "Start" submit input is clicked, I want the "start" view to use the {{ source.title}}
data in a function before returning a rendered page. How do I gather information POSTed (in this case, in the hidden input) into Python variables?
Django pass POST data to view You can define this URL in the urls.py file. In this URLs file, you can define the function created inside the view and access the POST data as explained in the above method. You just have to use the HTTPRequest. POST object to fetch POST data.
The result of request. method == "POST" is a boolean value - True if the current request from a user was performed using the HTTP "POST" method, of False otherwise (usually that means HTTP "GET", but there are also other methods).
class QueryDict. In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict , a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple> , pass multiple values for the same key.
Read about request objects that your views receive: https://docs.djangoproject.com/en/dev/ref/request-response/#httprequest-objects
Also your hidden field needs a reliable name and then a value:
<input type="hidden" name="title" value="{{ source.title }}">
Then in a view:
request.POST.get("title", "")
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