Extracting array with indices from GET parameters in Django

Viewed 598

My Django project has a page that features a table powered by DataTables. In this case, the table uses server-side processing using a Django view and the GET http method. The Django view unpacks the query string into a QueryDict object, and my task is to unpack the DataTables parameters for each column of the table from this QueryDict. Note that I must use GET, not POST, because I want to use the POST method for other things that actually change data on the server.

DataTables submits data for each column in the table relating to search strings and sorting for each column. This data is submitted as per their documentation here; the main point is that columnar params are sent up in the query string like this:

...&column[5][search][value]=searchme&column[6][search][value]=more&...

I would like this to be unpacked in such a way that the resultant data structure looks something like this:

column = [
    {
        'search': {
            'value': 'searchme'
        }
    },
    ...

]

...With the elements of the array submitted in the query string in the order specified by their indices.

Is there a standard way of accomplishing this with Django's QueryDict?

2 Answers

Source : https://gist.github.com/ijharulislam/28e9743e68a165dff0e4d1669644c4ba

def get_html_array(query_dict, param):
    dictionary = {}
    regex = re.compile('%s\[([\w\d_]+)\]' % param)
    for key, value in query_dict.items():
        match = regex.match(key)
        if match:
            inner_key = match.group(1)
            regex_sec = re.compile('%s\[%s\]\[([\w\d_]+)\]' % (param, inner_key))
            match_second = regex_sec.match(key)
            if match_second:
                dictionary[inner_key] = get_html_array(query_dict, '%s\[%s\]' % (param, inner_key))
            else:
                dictionary[inner_key] = value

    return dictionary

How to use :

 <form method="post">
   <input type='text' name='search[1][field]'>
   <input type='text' name='search[1][value]'>
   <input type='text' name='search[2][field]'>
   <input type='text' name='search[2][value]'>
   ...
 </form>
searchFields = get_html_array(request.POST, 'search')

You'll get :

{
  "1": {
    "field": "...",
    "value": "..."
  },
  "2": {
    "field": "...",
    "value": "..."
  }
}

Have fun.

It looks like Django does not implement this. At this point, it looks like the only options I have are to either:

  1. Use a library (like Satendra suggested in their comment on the question), or
  2. Write a custom parser that works on either the raw query string, or on the QueryDict object that is already available in Django class-based views, or
  3. Change the data that is sent to the Django view so that it is not multi-dimensional.

In this case, I've opted for the third choice; I'm modifying the data DataTables sends to the server so that it can be passed directly to a FilterSet or Form class constructor unmodified.

Related