Search code examples
pythondjangoposthttp-posthttprequest

How to get POST request values in Django?


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?


Solution

  • 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", "")