Django - taking values from POST request

PythonDjangoPost

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables

Solution 3 - Python

For django forms you can do this;

form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))

Solution 4 - Python

You can use:

request.POST['title']

it will easily fetch the data with that title.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRandall MaView Question on Stackoverflow
Solution 1 - PythonjdiView Answer on Stackoverflow
Solution 2 - Pythondm03514View Answer on Stackoverflow
Solution 3 - PythonIrfan waniView Answer on Stackoverflow
Solution 4 - PythonAkshat SharmaView Answer on Stackoverflow