Django – taking values from POST request

Posted on

Question :

Django – taking values from POST request

I have the following django template (http://IP/admin/start/ is assigned to a hypothetical view called view):

{% for source in sources %}
    <td>{{ source }}</td>

    <form action="/admin/start/" method="post">
      {% csrf_token %}
      <input type="hidden" name="{{ source.title }}">
      <input type="submit" value="Start" class="btn btn-primary">

{% 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?

Answer #1:

Read about request objects that your views receive:

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", "")
Answered By: jdi

Answer #2:

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

Answered By: dm03514

Answer #3:

For django forms you can do this;

form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = #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))
Answered By: Irfan wani

Leave a Reply

Your email address will not be published. Required fields are marked *