Django parsing angular post data

Source: Internet
Author: User
In the process of using Django and angular, there was a problem with a angular to the Django post data.

Angular$http ({    URL: "Myviews",    Method: "POST",    data: {' text ': ' Hello World ', ' Date ': ' 2017-01-04 '}})
# djangodef Myviews (Request):    print request. POST    Print Request.body

The above will print out

<querydict: {}>u "{' text ': ' Hello World ', ' Date ': ' 2017-01-04 '}"

And we expect this to be the result

<querydict: {u ' text ': U ' Hello World ', u ' date ': U ' 2017-01-04 '}>u ' {' text ': ' Hello World ', ' Date ': ' 2017-01-04 '} '

This problem occurs because the data format that angular sends by default is JSON not urlencode , and Django request.POST cannot parse JSON it, so the results above will appear.

There are many ways to solve this, and the simplest and most brutal approach is to parse it in every view function. request.body

def myviews (Request):    data = UrlEncode (Json.loads (request.body))    Q_data = querydict (data)

We can extract this type of operation and write it Middlerware in a request uniform process before the request reaches the view function.

class jsonmiddleware (object): "" "Process Application/json requests data from G    ET and POST requests. "" "Def process_request (self, request): If ' Application/json ' in Request.            meta[' content_type ': data = Json.loads (request.body) Q_data = Querydict (", mutable=true)                        For key, value in Data.iteritems (): If Isinstance (value, List): For x in Value:  Q_data.update ({key:x}) else:q_data.update ({key:value}) if Request.method = = ' GET ': request. GET = Q_data if Request.method = = ' POST ': request. POST = q_data return None 

Because request there is no CONTENT-TYPE such request Header , we need to judge that the reason is not simply translated into Dict the QueryDict principle of consistency, we want to bind the results to request.GET or request.POST above, and they are all QueryDict types. QueryDictand Dict The biggest difference is that QueryDict each value exists in the list, and QueryDict is a non-modifiable type. So value we have to make a decision when it comes to the list, otherwise the entire list will be stored as an element QueryDict in the list.

A = {"A": [123, 456, 444], "B": 456}# do not judge data = Querydict (", mutable=true) for K, V in A.iteritems ():    data.update ({k  : v}) Print data# make judgment data = Querydict (' mutable=true) for K, V in A.iteritems ():    if Isinstance (V, list): For        x in Value:            data.update ({k:x})    else:        data.update ({k:v}) print data
<querydict: {u ' a ': [[123, 456, 444]], u ' B ': [456]}><querydict: {u ' a ': [123, 456, 444], u ' B ': [456]}>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.