Django Rest Framework-设置视图

时间:2018-08-22 15:15:29

标签: reactjs django-rest-framework django-templates django-views django-urls

我已经在django中玩了一段时间了,但是对django rest框架来说是新手。我正在尝试设置视图,但我似乎只能获得的视图只有主页,该主页只有一个搜索栏和根api视图。

根api视图: enter image description here

我正在尝试显示项目列表,但这是我所能获得的。我还没有找到任何使用模板的教程来显示类似典型django的列表(而不是drf),但是我发现了很多使用DRF和反应的教程。有没有办法使用网址,视图和模板来做到这一点?还是只有答案?

这是我的树和使用的相关代码:

树:

YNB
src
    ├── YNB
    │   ├── __init__.py
    │   ├── __pycache__
    │   ├── settings.py
    │   ├── urls.py
    │   ├── views.py
    │   └── wsgi.py
    ├── __init__.py
    ├── accounts
    │   ├── __init__.py
    │   ├── __pycache__
    │   ├── admin.py
    │   ├── api
    │   │   ├── __init__.py
    │   │   ├── __pycache__
    │   │   ├── permissions.py
    │   │   ├── serializers.py
    │   │   ├── tests.py
    │   │   ├── urls.py
    │   │   ├── user
    │   │   │   ├── __init__.py
    │   │   │   ├── __pycache__
    │   │   │   ├── serializers.py
    │   │   │   ├── tests.py
    │   │   │   ├── urls.py
    │   │   │   └── views.py
    │   │   ├── utils.py
    │   │   └── views.py
    │   ├── apps.py
    │   ├── forms.py
    │   ├── migrations
    │   │   ├── __init__.py
    │   │   └── __pycache__
    │   ├── models.py
    │   ├── templates
    │   │   └── accounts
    │   │       ├── create_account_form.html
    │   │       ├── login.html
    │   │       └── signup.html
    │   ├── tests.py
    │   └── views.py
    ├── books
    │   ├── __init__.py
    │   ├── __pycache__
    │   ├── admin.py
    │   ├── api
    │   │   ├── __init__.py
    │   │   ├── __pycache__
    │   │   ├── serializers.py
    │   │   ├── tests.py
    │   │   ├── urls.py
    │   │   └── views.py
    │   ├── apps.py
    │   ├── forms.py
    │   ├── migrations
    │   │   ├── __init__.py
    │   │   └── __pycache__
    │   ├── models.py
    │   ├── templates
    │   │   └── books
    │   │       ├── _book.html
    │   │       ├── book_confirm_delete.html
    │   │       ├── book_detail.html
    │   │       ├── book_form.html
    │   │       ├── book_list.html
    │   │       └── user_book_list.html
    │   ├── tests.py
    │   └── views.py
    ├── db.sqlite3
    ├── manage.py
    ├── static
    │   └── YNB
    │       ├── css
    │       │   └── master.css
    │       └── js
    │           └── master.js
    └── templates
        ├── base.html
        ├── index.html
        ├── test.html
        └── thanks.html

根URLS

from django.conf.urls import url, include
from django.contrib import admin
from . import views


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.HomePage.as_view(), name='home'),
    # url(r'^api/auth/', include('accounts.api.urls', namespace='api-auth')),
    url(r'^api/user/', include('accounts.api.user.urls', namespace='api-user')),
    url(r'^api/books/', include('books.api.urls', namespace='api-books')),

图书网址

from django.conf.urls import url, include
from .views import (
                BookAPIView,
                BookAPIDetailView,
                )


urlpatterns = [
    url(r'^$', BookAPIView.as_view(), name='list'),
    url(r'^(?P<id>\d+)/$', BookAPIDetailView.as_view(), name='detail'), #shift to id because of lookup field # <pk> is built in method for giving view id. api/status/12
]

books views.py

import json
from rest_framework import generics, mixins, permissions
from rest_framework.authentication import SessionAuthentication # neccessary for user authentication
from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import get_object_or_404

from accounts.api.permissions import IsOwnerOrReadOnly
from books.models import Books
from .serializers import BooksSerializer


def is_json(json_data):
    try:
        real_json = json.loads(json_data)
        is_valid = True
    except ValueError:
        is_valid = False
    return is_valid


class BookAPIDetailView(
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    generics.RetrieveAPIView):
    permission_classes      = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]    # authentication_classes  = []
    serializer_class        = BooksSerializer  # necessary
    queryset                = Books.objects.all()
    lookup_field            = 'id'

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def patch(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)


# Login required mixin / decorator
class BookAPIView(
    mixins.CreateModelMixin,
    generics.ListAPIView):
    permission_classes          = [permissions.IsAuthenticatedOrReadOnly] # have to be logged in# if IsAuthenticatedOrReadOnly, non-logged in user cannot post, data is only read only # this demands that the person had to be authenticated inorder to do the things in this view. ie: create a post
    serializer_class            = BooksSerializer #necessary
    passed_id                   = None
    search_fields               = ('user__username', 'content', 'user__email')
    ordering_fields             = ('user__username', 'timestamp')
    queryset                    = Books.objects.all()

    template_name = "books/book_list.html"


    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)
        #comes from model mixin

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

books_list.html

{% extends "base.html" %}

{% block book_content %}
<div class="col-md-8">
    {% for book in book_list %}
        {% include "books/_book.html" %}
    {% endfor %}
</div>
{% endblock %}

提前谢谢大家。你们真棒。

0 个答案:

没有答案