1

I'm using Django and have a view to get/insert some records in database. Here's my code:

class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
    content = JSONRenderer().render(data)
    kwargs['content_type'] = 'application/json'
    super(JSONResponse, self).__init__(content, **kwargs)

@api_view(('GET','POST'))
@renderer_classes((TemplateHTMLRenderer,))
@csrf_exempt
def cours_list(request):

    if request.method == 'GET':
       data = JSONParser().parse(request)
       results = Lesson.objects.get(discipline=data.discipline)
       return Response({'cours': results}, template_name='search_results.html')

    elif request.method == 'POST':
       data = JSONParser().parse(request)
       serializer = LessonSerializer(data=data)
       if serializer.is_valid():
           serializer.save()
           return JSONResponse(serializer.data, status=201)
       return JSONResponse(serializer.errors, status=400)

So to get data I use GET and to insert a new record I use POST. First, is this the right way to do ? I read once that it't a bad idea to use GET whatever the situation. Also, the GET code is not actually working (I'm getting a bad request error) and it seems that this is comming from JSONParser that is not able to parse the request.

Edit1

Here is the request that is sent:

GET http://127.0.0.1:8000/cours/?{%22discipline%22:%22Mathematiques%22,%22localisation%22:%22%22}

Edit2

I tried to print requet.GET, and this what it gives:

<QueryDict: {'{"discipline":"Mathematiques","localisation":""}': ['']}>

When trying to access request.data['discipline'], it says:

django.utils.datastructures.MultiValueDictKeyError: "'discipline'"

Spider
  • 875
  • 2
  • 9
  • 27
  • I would like to suggest you post your entire view, because it's not clear if you're trying to use a regular Django view function, or if you want to use Django REST Framework's JSONParser etc Also if you can post a `curl` command that you use to send the requests (it helps others reproduce your problems so they can help you) – bakkal Feb 14 '16 at 15:02
  • @Bakkel. I'm indeed trying to use Django REST. – Spider Feb 14 '16 at 15:23

2 Answers2

3

Should I use GET or POST to retrieve results Django

To retrieve use a GET

I read once that it't a bad idea to use GET whatever the situation

Not at all, as long as your GET operation contains no side effects (e.g. in your GET method you are only reading from the database.

The GET code is not actually working (I'm getting a bad request error)

  data2 = JSONParser().parse(request) # you used data2
  results = Lesson.objects.get(discipline=data.discipline) # and you used data
                                          ^
                                          |____ data? data2?

You're not passing the GET parameters correctly

You need to pass GET params like this url/?param1=value1 To read that value you use param1 = request.GET['param1'] and param1 will be the string value1

What you are doing isn't passing a value:

GET http://127.0.0.1:8000/cours/?{%22discipline%22:%22Mathematiques%22,%22localisation%22:%22%22}

That's why you get an empty value ['']

<QueryDict: {'{"discipline":"Mathematiques","localisation":""}': ['']}>

You can pass the entire data as a JSON string if you want, but I prefer to break it down like this:

url/?discipline=Mathematiques&localisation=Quelquechose

with

discipline = request.GET['discipline']
localisation = request.GET['localisation']
bakkal
  • 54,350
  • 12
  • 131
  • 107
  • Thank you Bakkal, I understand better now. I editted the post, that was a mistake. I still have an error with parse function which does not seem to work. – Spider Feb 14 '16 at 12:12
  • I think you want to parse(request.GET) or parse(request.data), not parse(request), can you please try that? – bakkal Feb 14 '16 at 12:16
  • I just tried both, it says that `QueryDict has no attribute read` – Spider Feb 14 '16 at 12:19
  • You can get the parameters directly from the QueryDict, or use the JSONParser properly: http://www.django-rest-framework.org/api-guide/parsers/#setting-the-parsers – bakkal Feb 14 '16 at 12:29
1

That's absolutely normally to use GET method for information retrieving, see HTTP/1.1: Method Dediniton, 9.3:

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.

For POST method, it's a good practice to submit new data with POST request, see HTTP/1.1: Method Dediniton, 9.5:

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

  ................................................................
  - Providing a block of data, such as the result of submitting a
    form, to a data-handling process;
  - Extending a database through an append operation.

Also, take a look at Which HTTP methods match up to which CRUD methods? it will give you more clear idea of how and when particular HTTP methods shall be used and help you in next further development.

Art
  • 2,836
  • 4
  • 17
  • 34
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82