Accessing request parameters django - django

Hi I am trying to capture sms parameters from a request that comes in this format
b'name=kcom-sms04&number=%2B255688121131&content=Hello'
Above appears when I print HttpRequest.body
How can I access number, content and name parameters? I use django.

Short answer: use request.POST.
Normally these are POST parameters, you can access these with request.POST [Django-doc], which is a QueryDict [Django-doc]. A QueryDict is a dictionary-like object, but where a key can map to multiple values.
For example, you can access 'kcom-sms04' with request.POST['name'].

Related

what's the value type of the value of request.POST in django?

This is from print(request.POST)
<QueryDict: {'csrfmiddlewaretoken': ['2Tg4HgJ07qksb3hPUDWSQYueYOjYOkQcmzll9fnjbJ0GZHkWHdM8DtYqZB4uv3Fv'], 'username': ['boycececil'], 'password': ['password']}>
This is from print(request.POST.get('username'))
boycececil
So as you can see, list (from one of the values of QueryDict)-> string(from the get function), that's magic! Isn't it?
So, somebody know what's going on?
What the value type of the value of request.POST in django?
The type is django.http.request.QueryDict
So as you can see, list -> string, that's magic! Isn't it?
No, it isn't magic. This is just the documented behavior of QueryDict:
"QueryDict.__getitem__(key)
Returns the value for the given key. If the key has more than one value, it returns the last value. ..."
Note: if you want all values for a key, you can call getlist(key) on the QueryDict.
So, the request.POST is a subclass of the dictionary but not a raw dictionary.
It is a subclass of the django MultiValueDict class which is a subclass of dict.
When I call get(key) to the Querydict it return the last value of the list. Sounds like the get method in Querydict overwrite the get method in the raw dictionary.
Yes ... that is what the __getitem__ method does.
By the way, I wonder why we need multiple value for one key.
It is because HTTP allows multiple values for a given parameter in a request. So if multiple values can be provided, django need to be able to make them available via the HttpRequest.POST object.
But since this is an unusual case, they decided to just give your code one value for each parameter ... unless it specifically asks for them all. Django is being helpful.

Django: pass some paremeter to view in Django urls

I want to pass some string for some urls to my views in django
Suppose i have
path('someurl/', someview , name='someurl'),
I want to pass some string to someview, when this url is called so is this possible
path('someurl/', someview(somevar="test") , name='someurl'),
and then i have the view
def someview(request, somevar):
access somevar here
Is this possible in Django urls.
If you wish to accept parameter from the client, update your path as below:
path('someurl/<str:somevar>/', someview , name='someurl')
And view now can accept extra parameter:
def someview(request, somevar):
# now you can use somevar
With this definition, if client requests somevar/urlparam/, "urlparam" will be passed to you view function.
Otherwise if you want to provide your own argument, Django doesn't provide the way to do it directly in url definition. But, since that variable is your own one, why don't assign (or compute) that in view? I mean:
def someview(request):
somevar = "test" # or you may call some function for dynamic assignment
# now somevar exists in this scope, so you can use it as you want
yes it is possible. You need to define those parameters in the url as pseudo path:
path('articles/<int:year>/<int:month>/', views.month_archive),
There is also an option to use request.GET and request.POST to access the optional parameters list in the url:
request.POST.get('<par name here>','<default value here>')
request.GET.get('<par name here>','<default value here>')
Another thing you may find useful is this question.

QueryDict getlist returns empty list

I'm sending from frontend object with one property which equal to array.
In backend I need to get data from that array.
when i write request.POST i see:
<QueryDict: {u'response[0][doc_id]': [u'14'], u'response[1][uuid]': [u'157fa2ae-802f-f851-94ba-353f746c9e0a'], u'response[1][doc_id]': [u'23'], u'response[1][data][read][user_ids][]': [u'9'], u'response[0][uuid]': [u'8a0b8806-4d51-2344-d236-bc50fb923f27'], u'response[0][data][read][user_ids][]': [u'9']}>
But when i write request.POST.getlist('response') or request.POST.getlist('response[]') i get
[]
request.POST.get('response') doesn't work as well (returns None).
What is wrong?
Because you don't have either response[] or response as keys, you have the literal strings response[0][doc_id] and response[1][uuid] etc.
If you want to use a structure like this, you should send JSON rather than form-encoded data and access json.loads(request.body).

Django 1.6 request POST/GET empty

I use a function-based view and try to validate a form which is submitted over Ajax (with jquery.form plugin):
Content-Type:application/json; charset=UTF-8
X-CSRFToken:jRr4oOBHQS5mtwopN69xHocjWJBYuJHa
X-Requested-With:XMLHttpRequest
Request payload:
csrfmiddlewaretoken=jRr4oOBHQS5mtwopN69xHocjWJBYuJHa&code=123456
now, in the view function, I have request.GET/POST empty, but request.body as a string, and I can't validate the form.
form = CodeCheckForm(parse_qs(request.body))
form.is_valid()
In the second line, the clean* functions aren't called, which is really weird.
Changing to use data or initial doesn't help either:
form = CodeCheckForm(data=parse_qs(request.body))
What am I doing wrong?
EDIT: among the answers, the decisive was to change the content type. In jquery.forms plugin I set contentType option to application/x-www-form-urlencoded; charset=UTF-8.
EDIT 2: there are 2 ways to supply arbitrary data around the standard way, but they weren't suitable in my case:
1) form = MyForm(parse_qs(request.body)) is almost correct, but Django forms expect this to be a QueryDict, and have some properties, while this is a usual dict. Form class raises exception and crashes the view.
2) form = MyForm(data=parse_qs(request.body)) works, but does not call clean* functions. This is intentional, as Django developers made this way as a way around clean functions. You're supposed to validate the data yourself, and then submit it this way. Django form then does not clean it in any way and decides the form is not validated, hence form.is_valid() will be False.
The GET and POST only contain form data. They are empty for you because your content type is 'application/json'. It's not clear to me why you've used this content type, since the payload looks like form encoded data to me, not json.
If you manually parse the payload, use the data argument. The initial argument is only used to show initial values. If you don't bind the form to data, then the form is unbound, and will never be valid.
I'm not sure why the following line didn't work. What is the value of parse_qs(request.body)?
form = CodeCheckForm(parse_qs(request.body))

Django, Pass QuerySet to url using redirect/redirect_to

How can I redirect from view to another url, passing my queryset to another view?
I tried this:
return simple.redirect_to(request, 'some_url', **{'queryset': results})
and this
return redirect('some_url', queryset=results )
but it does not work....
How can i do it?
Gabi.
How are you expecting this to work? Redirection happens by getting the browser to request another URL. Anything you want to pass as a parameter to the redirection must therefore go into the URL you're redirecting to. It simply doesn't make sense to put a queryset into a URL parameter.
Presumably you could pass whatever arguments you used to get the queryset in the first place, but that's a lot of extra work.
Do you really need to redirect at all? What about simply calling the new view from your original one, and returning its response?