Django REST API with multiple views / formats

I am new to web designer and I am trying to create a project to create a Restful web api and website. I use the Django framework and the following tutos, I always see html files as static and different views displaying an html template. This way of doing it seems to me that the backend and interface are not separate. Is it possible for the backend to be developed only in Django?

change

I actually have a more specific problem. I have this application (records) with the "patient_list" view using the Response class from the REST environment, which displays some data and an html template as follows:

def patient_list(request):
"""
List all records, or create a new .
"""
if request.method == 'GET':
    #data = Patient.objects.all()
    data= Patient.objects.all()
    #serializer = PatientSerializer(data, many=True)
    #return JSONResponse(serializer.data)
    return Response({'patients': data}, template_name='records.html')

in my urls.py I have:

url(r'^records/$', views.patient_list),

. , /records, _ html-. , ( , ), restful API , "frontend" (html- ). ? , Response html-?

+4
1

Vanilla Django

, , - Django.

. Django, JSON , HTML- . API "-".

JsonResponse

from django.views.generic import View
from django.http import JsonResponse

class MyView(View):
    def get(self, request):
        my_data = {'something': 'some value'}
        return JsonResponse(my_data, mimetype='application/json')

, HTML Django, , .

REST

, , API RESTful Django, Django REST Framework Tastypie

- .

REST API. . HTML, JSON. :

  • GET ?format=JSON ( HTML, .)
  • Accept
  • URL /records.html /records.json ( )

DRF

. GET, :

if request.method == 'GET':
    data = Patient.objects.all()
    format = request.GET.get('format', None)

    if format == 'JSON': 
        serializer = PatientSerializer(data, many=True)
        return JSONResponse(serializer.data)
    else:
        # Return HTML format by default
        return Response({'patients': data}, template_name='records.html')
+6

Source: https://habr.com/ru/post/1626749/


All Articles