user3600840
user3600840

Reputation:

How to connect with Django REST framework to front-end

I'm new on Django REST Framework. I have an index.html where I have simple form for adding items and back-end with Django. I can't understand, how I can connect index.html to Django REST Framework. I have the next code-files:

models.py

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    category = models.CharField(max_length=100)

    def __str__(self):
        return self.title

views.py

from django.shortcuts import render
from django.views.generic import TemplateView
from .models import Book
from rest_framework import viewsets
from .serializers import BookSerializer

class Index(TemplateView):
    template_name = "index.html"
    def get_context_data(self):
        context = super(Index, self).get_context_data()
        return context


class BookViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Book.objects.all().order_by('title')
    serializer_class = BookSerializer

urls.py

from django.conf.urls import url, include
from rest_framework import routers
from myapp import views

router = routers.DefaultRouter()
router.register(r'books', views.BookViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^$', views.Index, name='index'),
]

serializers.py

from .models import Book
from rest_framework import serializers

class BookSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Book
        fields = ('title','category')

And if I run localhost:8000/index I get an error 'Page not found'. I can't understand how correct I should include my html pages to the django code. Should I use a router.register for this?

Upvotes: 4

Views: 11315

Answers (2)

iulian
iulian

Reputation: 5812

Let's start by defining what django-rest-framework is and what it is not.

It is a nice toolkit to build web APIs. This means that you can define several endpoints (urls) that will handle incoming requests and will return a response in JSON or XML format.

It is not an html rendering tool though. This means that you can't return a response that contains html code to be rendered as a page in the browser. It will return pure json or xml data.

Now, your questions consists of 2 problems:

  1. You can't access the index.html page.
  2. You don't know how to connect this page with the books endpoint.

Regarding problem 1

Check the TEMPLATES settings. Where is your index.html placed? Does django know where to find it? Check out the TEMPLATES setting and assure you have set it up correctly.

Regarding problem 2

Because of the fact that the django-rest-framework endpoint handles incoming requests, you need to generate such a request. But if you will simply access the endpoint in your browser, the page will load/reload and you will see the data from your endpoint in json form on your page.

For your page to remain the same, but at the same time to make a request to your endpoint, you need to use ajax (Asynchronous JavaScript and XML) from within your index.html page. You can emit an ajax request by using one of the following:

  1. With pure JavaScript, by means of XMLHttpRequest class. See this SO question and answers to see how this is made.
  2. If you use jQuery, it has a jQuery.ajax() method to make an ajax request.
  3. If you use any other frontend framework (angular, backbone, ember, etc.), all they have an implementation of ajax calls. Check their documentation for that.

And basically that's it. Good luck!

Upvotes: 9

Mounir
Mounir

Reputation: 11726

Could you try putting the api url after your index like this?

urlpatterns = [
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^$', views.Index, name='index'),
    url(r'^', include(router.urls)),
]

Or why not use /api/ for your REST Api urls:

urlpatterns = [
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^$', views.Index, name='index'),
    url(r'^api/', include(router.urls)),
]

And be sure that you have added 'rest_framework', to INSTALLED_APPS

EDIT:

To access /index/ you must fix your urls.py:

urlpatterns = [
    url(r'^index/$', views.Index, name='index'),
    url(r'^api/', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

Upvotes: 2

Related Questions