stephan
stephan

Reputation: 2403

How to return json using django rest and see it from the browser

I am following the django rest tutorial and I think I am doing something incorrectly with my views. All I'm trying to do is return all the objects for Entry class in JSON, and have it be viewable from within the browser. Currently when I go to api/storefront, I get a 500 error.

views.py

@api_view(['GET', 'POST'])
def EntryAPI(request):
    snippets = Entry.objects.all()
    serializer = EntrySerializer(snippets, many=True)
    return Response(serializer.data)

urls.py

urlpatterns = patterns('',
    (r'^api/storefront/$', EntryAPI),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

The method below returns all the records for the Entry class, so I'm not sure why the Django rest stuff is not doing the same or why I'm getting the 500 error. Also I've confirmed that my serializers.py and models.py is not the issue.

def storefront(request):
    if request.user.is_authenticated():
        latest_entries = Entry.objects.all()
        context = {'latest_entries': latest_entries}
    return render(request, 'storefront.html', context)

Upvotes: 0

Views: 364

Answers (1)

Pawan
Pawan

Reputation: 4419

I normally prefer using class based views , and I got stuck into 500 error during learning stage when I was not using as_view() (for CSRF protection) in my urls like below.

url('^login/$', views.LoginView.as_view())

which cant be done in function based view. Why dont you use @csrf_exempt above your function like below.

@api_view(['GET', 'POST'])
@csrf_exempt
def EntryAPI(request):
    snippets = Entry.objects.all()
    serializer = EntrySerializer(snippets, many=True)
    return Response(serializer.data)

or you should try (r'^api/storefront/$', EntryAPI.as_view()), in your urls.py

Upvotes: 4

Related Questions