如何解决未指定`basename`参数
我由django restframework创建了一个新项目 项目名称=框架 th project_app name = framework
fram.urls.py:
"""frame URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('',views.home,name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('',Home.as_view(),name='home')
Including another URLconf
1. Import the include() function: from django.urls import include,path
2. Add a URL to urlpatterns: path('blog/',include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path
from django.conf.urls import include,url
from framework.views import myviewset
from rest_framework import routers
router = routers.DefaultRouter();
router.register('task',myviewset)
urlpatterns = [
path('admin/',admin.site.urls),re_path(r'',include(router.urls)),]
框架模型。py:
from django.db import models
# Create your models here.
class Task (models.Model):
task_name=models.CharField(max_length='200')
task_desc=models.CharField(max_length='200')
date_created=models.DateTimeField(auto_Now=True)
serializer.py
from .models import Task
from rest_framework import serializers
class TaskSerializers(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('id','task_name','task_desc')
views.py:
from django.shortcuts import render
from .serializer import TaskSerializers
from rest_framework import viewsets
from .models import Task
# Create your views here.
class myviewset(viewsets.ModelViewSet):
query = Task.objects.all().order_by('date_created')
serializer_class = TaskSerializers
admin.py:
from django.contrib import admin
from .models import Task
admin.site.register(Task)
# Register your models here.
setting.py:
INSTALLED_APPS = [
'framework','rest_framework','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]
当我在CMD中运行服务器时 错误出现:
AssertionError:basename
参数未指定,并且由于没有.queryset
属性,因此无法从视图集中自动确定名称。
解决方法
您应该在视图集中指定queryset
属性而不是query
。例如(类别名称大小写已更改为符合PEP8):
class MyViewSet(viewsets.ModelViewSet):
queryset = Task.objects.all().order_by('date_created')
serializer_class = TaskSerializers
文档:https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset
此外,我建议您在注册视图集时始终指定basename
。像这样:
router = routers.DefaultRouter();
router.register('task',MyViewSet,basename='tasks')
https://www.django-rest-framework.org/api-guide/routers/#usage
basename
-用于创建的URL名称的基础。如果未设置,则将基于视图集的queryset
属性自动生成基本名称。请注意,如果视图集不包含queryset
属性,则在注册视图集时必须设置basename
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。