基于类的视图的urls.py格式是什么?

时间:2017-07-23 20:38:19

标签: django

我是django的新手所以我想知道如何为项目编写urls.py。 我想为库存管理系统制作后端api。 当我键入localhost:8000 / inventory_backend / dep /时,我遇到以下错误: **使用mysite.urls中定义的URLconf,Django按以下顺序尝试了这些URL模式: 当前路径inventory_backend / dep /与其中任何一个都不匹配。

我的mysite / urls.py **代码

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



   urlpatterns =  [
              url(r'^inventory_backend/', include('inventory_backend.urls') 
   ),
               url(r'^admin/', admin.site.urls) ,
             ]

inventory_backend / urls.py:

 from inventory_backend.views import DepartmentsView,InventoriesView

 from rest_framework import routers

router = routers.SimpleRouter()

router.register(r'dep/',DepartmentsView )

router.register(r'inv/',InventoriesView )

 urlpatterns = router.urls

serializers.py

from rest_framework import serializers

from inventory_backend.models import Departments,Inventories


class DepartmentsSerializer(serializers.ModelSerializer):
class Meta:
    model : Departments
    fields: ('id','name')


 class InventoriesSerializer(serializers.ModelSerializer):
dept = DepartmentsSerializer(many=True)
class Meta:
    model : Inventories
    fields : ('id','name','description','dept')

models.py

from django.db import models


class Departments(models.Model):
name = models.CharField(max_length=200)

def __str__(self):
    return self.name


class Inventories(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
dept = models.ManyToManyField(Departments)

def __str__(self):
    return self.name

views.py

from rest_framework import viewsets
from inventory_backend.models import Inventories,Departments
from inventory_backend.serializers import InventoriesSerializer, 
DepartmentsSerializer


class DepartmentsView(viewsets.ModelViewSet):
queryset = Departments.objects.all();
serializer_class = DepartmentsSerializer;



class InventoriesView(viewsets.ModelViewSet):
queryset = Inventories.objects.all();
serializer_class  = InventoriesSerializer;

1 个答案:

答案 0 :(得分:0)

更改inventory_backend.urls.py,

urlpatterns = [
    url(r'^', include(router.urls))
        ]