How to get values from Post Method

I have a form which as a input field (List). I would like to access that field individually. My code is below with output what i get.

 def alltestdata(request):
    if request.method == 'POST':
      username = request.POST
      print(username)
  return redirect('lab:Dashboard')

My output will come something like this

         <QueryDict: {'csrfmiddlewaretoken':      ['vPkRRW9dCFLRRmVAm3PlOS1MURkZ6pSLBxz6ryEuVkwzuD2vW6mlWstFYxF2T4Tx'], 'name': ['gg', 'rr', 'rr','ee']}>

Upvotes: 0

Views: 1632

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476604

The request.POST is a QueryDict containing all the elements that have been posted.

If you want the list of all elements attached to a specific key, you can use the QueryDict.getlist:

request.POST.getlist('name')  # => ['gg', 'rr', 'rr','ee']

Or if you are interested in the last element that is attached to a given key, you can use indexing, or QueryDict.get():

request.POST['name']  # => 'ee'
request.POST.get('name')  # => 'ee'

The difference is that the former will raise an exception if no such key exists, whereas the latter will return None.

Upvotes: 3

Sumeet Kumar
Sumeet Kumar

Reputation: 1019

if request.method == 'POST':
  username = request.POST.get('username','')
  print(username)

this will get username from post body if present else blank string

Upvotes: 0

Related Questions