【发布时间】:2021-09-18 04:03:59
【问题描述】:
注意:我不是在寻求帮助来修复错误,而是通过交换 url 模式的顺序来询问它们不同的原因。 p>
以下是我的 django 应用程序 (basic_app) 的 urls.py 的样子:
from django.urls import path, re_path
from basic_app import views
app_name = 'basic_app'
urlpatterns = [
path('', views.SchoolListView.as_view(), name='list'),
re_path(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'),
path('create/', views.SchoolCreateView.as_view(), name='create'),
]
当我运行服务器并输入 url http://127.0.0.1:8000/basic_app/create/ 时,它会抛出以下错误:
ValueError at /basic_app/create/
Field 'id' expected a number but got 'create'.
Request Method: GET
Request URL: http://127.0.0.1:8000/basic_app/create/
Django Version: 3.2.4
Exception Type: ValueError
Exception Value:
Field 'id' expected a number but got 'create'.
有趣的是,当我将第二个和第三个 url 模式的顺序交换如下:
from django.urls import path, re_path
from basic_app import views
app_name = 'basic_app'
urlpatterns = [
path('', views.SchoolListView.as_view(), name='list'),
path('create/', views.SchoolCreateView.as_view(), name='create'),
re_path(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'),
]
我得到一个不同的错误:
ImproperlyConfigured at /basic_app/create/
Using ModelFormMixin (base class of SchoolCreateView) without the 'fields' attribute is prohibited.
Request Method: GET
Request URL: http://127.0.0.1:8000/basic_app/create/
Django Version: 3.2.4
Exception Type: ImproperlyConfigured
Exception Value:
Using ModelFormMixin (base class of SchoolCreateView) without the 'fields' attribute is prohibited.
我是 django 的新手,对这个事件感到好奇。为什么python不让create/去下一个模式检查,因为它不适合第一个模式?
我的views.py 文件如下所示:
from django.shortcuts import render
from django.views.generic import (
View,
TemplateView,
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from . import models
# Create your views here.
class IndexView(TemplateView):
template_name = 'index.html'
class SchoolListView(ListView):
context_object_name = 'schools'
model = models.School
class SchoolDetailView(DetailView):
context_object_name = 'school_detail'
model = models.School
template_name = 'basic_app/school_detail.html'
class SchoolCreateView(CreateView):
model = models.School
【问题讨论】:
-
能否分享一下相关的看法。
-
@WillemVanOnsem 我已经附加了
views.py脚本。
标签: python django url-pattern