如何将Django REST框架连接到前端

时间:2016-03-31 19:56:20

标签: python django django-rest-framework

我是Django REST Framework的新手。我有一个index.html,我有简单的表单来添加项目和后端与Django。我无法理解,我如何将index.html连接到Django REST Framework。 我有下一个代码文件:

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')

如果我运行localhost:8000 / index我会收到错误' Page not found'。我无法理解我应该将我的html页面包含在django代码中是多么正确。我应该使用router.register吗?

2 个答案:

答案 0 :(得分:7)

让我们首先定义django-rest-framework是什么,不是什么。

是构建web APIs的好工具包。这意味着您可以定义几个将处理传入requests的端点(网址),并以responseJSON格式返回XML

它不是一个html渲染工具。这意味着您无法返回包含html代码的response,以便在浏览器中呈现为页面。它将返回纯jsonxml数据。

现在,您的问题包含两个问题:

  1. 您无法访问index.html页面。
  2. 您不知道如何将此页面与books端点相关联。
  3. 关于问题1

    检查TEMPLATES设置。你的index.html放在哪里? django知道在哪里找到它吗?查看TEMPLATES setting并确保您已正确设置。

    关于问题2

    由于django-rest-framework端点处理传入的requests这一事实,您需要生成此类请求。但是,如果您只是在浏览器中访问该端点,该页面将加载/重新加载,您将在页面上以json形式查看端点中的数据。

    要让您的网页保持不变,但同时向您的终端发出请求,您需要在ajax页面中使用index.htmlAsynchronous JavaScript and XML)。您可以使用以下方法之一发出ajax请求:

    1. 使用纯JavaScript,通过XMLHttpRequest类。请参阅this SO问题和答案,了解如何制作。
    2. 如果您使用jQuery,则会有jQuery.ajax()方法发出ajax请求。
    3. 如果你使用任何其他前端框架(angular,backbone,ember等),他们都会实现ajax次调用。检查他们的文档。
    4. 基本上就是这样。祝你好运!

答案 1 :(得分:2)

你能尝试在你的索引之后输入api url吗?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<link rel="stylesheet" type="text/css" href="bootstrappopover.css">
<link rel="stylesheet" type="text/css" href="newraocss.css">
<title>Patricia S. Bowne fiction</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<!-- call javascript (necessary in the head for Bootstrap's JavaScript plugins) -->

   <script src="jquery-1.12.1.min.js"></script>
  <script src="bootstrappopover.js"></script>

 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>


<table class="border">

<tfoot>

<td class="footer" colspan=3>Copyright Patricia S. Bowne

</td>
</tfoot>

<tbody>

<tr>

<td class="header" colspan=3>
<div><br><h1>Patricia S. Bowne<h1></td>
</tr>

<tr> 

<td class="edge">


</td>


<td class="center"><p>Click on the title below each thumbnail for a description of the book, including links to purchase and read excerpts. To hide the description, click on the title again.</p>

<div class="books">
<div class="thumbnail"><img class="med" src="images/Pigeons-510.jpg"><br><a class="button" href="javascript://" data-toggle="popover" data-placement="top" title="" data-content="Some jobs are more trouble than they're worth ... 
the Demonology department's newest member, Hiram Rho, tries to gain his footing among colleagues with specialties like vampirology, classical lechery, and postmodern feminist demonology. Before Rho has been on campus a month he has acquired an affectionate demon with a plan to take over the department, the two senior demonologists have lost their souls and their health insurance, and Rho's problems have embroiled everyone from the mysterious Alchemy faculty to the pigeons on his window ledge. Available from:<br> <a href='http://www.double-dragon-ebooks.com/single.php?ISBN=1-55404-808-7' title='test add link'>Double Dragon E-Books</a><br><a href='http://www.amazon.com/Advice-From-Pigeons-ebook/dp/B004MYFSHU/' title='test add link'>Amazon Kindle store</a>" data-original-title="The Royal Academy I: Advice from Pigeons">The Royal Academy I:<br> Advice from Pigeons</a></div>
</div><script>$("[data-toggle=popover]")
.popover({html:true})</script>


<p><div class="reviews"><b>Reviewers say:</div>             
</td>
<td class="edge">
</td>
</tr>
</tbody>
</table>
</body>

或者为什么不将/ api /用于您的REST Api网址:

urlpatterns = [
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^$', views.Index, name='index'),
    url(r'^', include(router.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)), ] 添加到'rest_framework',

编辑:

要访问INSTALLED_APPS,您必须修复urls.py:

/index/