A
A
Alla Zakharova2017-03-24 06:56:12
Django
Alla Zakharova, 2017-03-24 06:56:12

How to extract data from POST request to json in Django?

There will be a feedback form (I do not do it). Implementation using standard Jungian forms was rejected.
The question arose of how to get a post-request from which the data was returned in json format, and then from json it was resaved separately to each model object (so that you could view the information left by users in the admin panel)?
Honestly, I don't understand how to do it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2017-03-24
@Mi5aka

It would be great if you could give an example of the form you need to work with and the format of the resulting json in your question.
It should be simple, get json from the frontend, convert it to a dictionary using json.loads() and pass the result to the form constructor in the same way as you normally pass request.POST

import json
from django import forms

class SomeForm(forms.Form):
    name = forms.CharField(label=u'Name', max_length=25)

def some_view(request):
    json_string = request.POST.get('json_data')
    form_data = json.loads(json_string)[0]
    f = SomeForm(form_data)
    if f.is_valid():
        name = f.cleaned_data['name']
        # ... Работа с данными ...
    else:
        # ... Обработка ошибки ...

M
Maxim, 2017-03-25
@maximkv25

def example(request):
    try:
        data = json.loads(request.body.decode())
    except ValueError:
        return JsonResponse({
            'error': 'bla bla bla',
        })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question