98

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?

Randall Ma
  • 10,486
  • 9
  • 37
  • 45

4 Answers4

177

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", "")
jdi
  • 90,542
  • 19
  • 167
  • 203
  • I use Django Forms where I don't have an independent `input` and just a `{{ form }}` and my form has only one text input (charfield). how can I access its data? – Nitwit Jan 20 '20 at 13:54
  • @Nitwit the `name` attribute will be the name of the property you assigned the charfield to. If your not 100% press F12 while in the browser with the form loaded and select the input element to see what Django gave the name attribute. – James Bellaby Jan 06 '21 at 16:43
15

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

dm03514
  • 54,664
  • 18
  • 108
  • 145
  • The other answer helped me with a problem I was going to ask you (definitions of name/value html selectors) before I asked it, so I'll go ahead and mark that one accepted. Thanks for your help though. :) – Randall Ma Jul 05 '12 at 00:27
5

You can use:

request.POST['title']

it will easily fetch the data with that title.

innicoder
  • 2,612
  • 3
  • 14
  • 29
Akshat Sharma
  • 51
  • 1
  • 2
4

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))
Irfan wani
  • 4,084
  • 2
  • 19
  • 34