DjangoRestFramework - 如何自定义前端? [英] DjangoRestFramework - How do I customize the frontend?

查看:16
本文介绍了DjangoRestFramework - 如何自定义前端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使用 DjangoRestFramework 的基本视图:

This is my basic view using DjangoRestFramework:

class user_list(APIView):
    """
    List all users, or create a new user.
    """
    def get(self, request):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = UserSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

当我转到调用此视图的 URL (localhost:8000/CMS/users) 时,DjangoRestFramework 已经有一个前端显示:

When I go to the URL which calls this view (localhost:8000/CMS/users), DjangoRestFramework already has a frontend which says:

GET /CMS/users
HTTP 200 OK
Vary: Accept
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json

[
    {
        "username": "t",
    }
]

如何自定义?我想在前端使用 AngularJS.我知道如果没有 DjangoRestFramework,我会返回一个 html 模板,该模板将位于我的 Django App 目录中名为Templates"的文件夹中.有人告诉我 DjangoRestFramework 很有用,因为我可以创建一个返回 JSON 对象的 RESTful API.我尝试将以下内容添加到我的 settings.py 文件中:

How do I customize this? I want to use AngularJS on the frontend. I know that without DjangoRestFramework, I would return an html template which would be located in my Django App directory in a folder called "Templates". I've been told that DjangoRestFramework is useful becauase I can create a RESTful API which returns JSON objects. I tried adding the following to my settings.py file:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    )
}

但我似乎仍然无法弄清楚如何自定义我的 Django 应用程序的前端.我知道有:

but I still can't seem to figure out how I can customize the frontend of my Django application. I know that there is:

renderer_classes = (TemplateHTMLRenderer,)

我可以在我的视图中返回一个 html 页面,如下所示:

in which I can return an html page in my view, like so:

return Response({'user': self.object}, template_name='user_detail.html')

但是返回实际的 HTML 页面是否违背了 DjangoRestFramework 返回 JSON 对象和创建 RESTful API 的能力的目的?

but doesn't returning actual HTML pages defeat the purpose of DjangoRestFramework's ability to return JSON objects and create a RESTful API?

推荐答案

首先,有一些事情可以让 Django Rest Framework 更好地使用 Angular.在我决定尝试 ember 之前,我一直在研究 本教程.尝试为您的问题提供一个有用的示例:

First off, there are some things to make Django Rest Framework play better with angular. Until I decided to try out ember, I was working through this utorial. To try to provide a useful example for your question:

  1. 通常你想把你的 DjangoRestFramework REST Api 放在类似/api 的地方.

  1. Typically you want to put your DjangoRestFramework REST Api in something like /api.

如果您正在做看似无处不在的单页应用程序,那么您可以将 index.html 作为模板提供(即,只需将您的默认主页视图设为以 index.html 作为模板的 TemplateView)

If you're doing the seemingly ubiquitiious single page application, you can then have index.html get served up as a template (i.e. just have your default home view be a TemplateView with index.html as the template)

然后你将拥有你的 Angular html 模板和你的 angular/jquery/etc.javsascripts 和你的 css 文件作为普通的静态文件.请注意,您通常不希望 django 模板生成角度代码.首先,它使调试变得更加痛苦,其次,默认的 angular 和 django 模板语法使用相同的 <% 字符,这意味着您必须小心确保不要尝试解释其他模板代码.

You would then have your angular html templates and your angular/jquery/etc. javsascripts and your css files as normal static files. NB that you generally don't want to have django templates generate angular code. First off, it makes things much more of a pain to debug, and secondly, the default angular and django template syntax use the same <% characters meaning you have to be careful to make sure one doesn't try to interpret the others templating code.

当您加载 http://yourserver/ 时,这将打开 index.html 页面,然后下拉有角度的内容,然后开始对您的 REST api 进行 RESTful 调用以生成数据.请注意,您可以开始混合使用 Django 表单等内容,但我建议您保持简单,然后在掌握基础知识后阅读链接的文章(或其他文章).

When you load http://yourserver/, this will bring up the index.html page which then pulls down angular stuff, which then starts making RESTful calls to your REST api to generate the data. Note that you can start mixing in stuff to use Django forms etc., but I'd recommend keeping it simple and then reading the linked article (or another) once you have the basics going.

这篇关于DjangoRestFramework - 如何自定义前端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆