Django - 即使参数正确(无命名空间)也出现 NoReverseMatch 错误
Django - NoReverseMatch Error even with correct parameters (no namespacing)
我正在尝试创建一个应用程序来存储问题(特别是数学问题),并将它们显示给用户。我还没有添加很多我想要的功能,因为我对 Django 还很陌生,所以我一直在关注 Django Tutorial 项目,并根据我的需要对其进行更改。但是,我遇到了 NoReverseMatch 错误,尽管我似乎传递了正确的参数。我的代码如下。
models.py
import imp
from django.db import models
from django.urls import reverse
import uuid
# Create your models here.
class Source(models.Model):
'''Model that represents the source of a problem (e.g. AMC, AIME, etc.)'''
problem_source = models.CharField(max_length=20)
problem_number = models.PositiveSmallIntegerField()
def __str__(self):
'''toString() method'''
return f'{self.problem_source} #{self.problem_number}'
class Topic(models.Model):
'''Model that represents the topic of a problem (e.g. Intermediate Combo)'''
problem_topic = models.CharField(max_length=50)
problem_level = models.CharField(max_length=15)
def __str__(self):
return f'{self.problem_level} {self.problem_topic}'
class Problem(models.Model):
'''Model that represents each problem (e.g. AIME #1, AMC #11, etc.)'''
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
source = models.OneToOneField(Source, on_delete=models.RESTRICT, null=True, unique=True)
problem_text = models.TextField()
topic = models.ManyToManyField(Topic)
def __str__(self):
"""String for representing the Model object."""
return f'{self.source}'
def get_absolute_url(self):
"""Returns the url to access a detail record for this book."""
return reverse('problem-detail', args=[str(self.id)])
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('problems/', views.ProblemListView.as_view(), name='problems'),
path('problem/<int:pk>', views.ProblemListView.as_view(), name='problem-detail'),
]
views.py
import imp
from django.shortcuts import render
# Create your views here.
from .models import Problem, Source, Topic
def index(request):
'''View function for home page of site'''
# generate counts of the main objects
num_problems = Problem.objects.all().count()
context = {
'num_problems': num_problems,
}
return render(request, 'index.html', context=context)
from django.views import generic
class ProblemListView(generic.ListView):
model = Problem
class ProblemDetailView(generic.DetailView):
model = Problem
我的 HTML 文件的链接如下:
base_generic.html: link
problem_list.html: link
problem_detail.html: link
我的工作区结构如下:
trivial
catalog
migrations
static/css
styles.css
templates
catalog
problem_detail.html
problem_list.html
base_generic.html
index.html
__init.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
trivial
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
我已阅读其他 Whosebug 帖子,但 none 似乎适用于我的情况。此外,在 problem_list.html 中,如果 href
link 中的值为 Problem.get_absolute_url
,站点将加载,但单击“所有问题”的 link 将返回同一页面。但是,如果我将 prob.get_absolute_url
放在 href
link 中,我会收到 NoReverseMatch 错误。
这是我得到的确切错误:
NoReverseMatch at /catalog/problems/
Reverse for 'problem-detail' with arguments '('41b936f7-3c08-4fb9-a090-2d466348d34d',)' not found. 1 pattern(s) tried: ['catalog/problem/(?P<pk>[0-9]+)\Z']
Request Method: GET
Request URL: http://127.0.0.1:8000/catalog/problems/
Django Version: 4.0.2
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'problem-detail' with arguments '('41b936f7-3c08-4fb9-a090-2d466348d34d',)' not found. 1 pattern(s) tried: ['catalog/problem/(?P<pk>[0-9]+)\Z']
Django 告诉我错误源于在 problem_list.html
中调用 prob.get_absolute_url
问题是 Problem
模型上的 id
是 UUID
,但 URL 模型需要一个整数值作为 pk
- 因为您已在命名模式前加上 int:
:
path('problem/<int:pk>', views.ProblemListView.as_view(), name='problem-detail'),
如果您将其更改为:
,它应该可以工作
path('problem/<uuid:pk>', views.ProblemListView.as_view(), name='problem-detail'),
我正在尝试创建一个应用程序来存储问题(特别是数学问题),并将它们显示给用户。我还没有添加很多我想要的功能,因为我对 Django 还很陌生,所以我一直在关注 Django Tutorial 项目,并根据我的需要对其进行更改。但是,我遇到了 NoReverseMatch 错误,尽管我似乎传递了正确的参数。我的代码如下。
models.py
import imp
from django.db import models
from django.urls import reverse
import uuid
# Create your models here.
class Source(models.Model):
'''Model that represents the source of a problem (e.g. AMC, AIME, etc.)'''
problem_source = models.CharField(max_length=20)
problem_number = models.PositiveSmallIntegerField()
def __str__(self):
'''toString() method'''
return f'{self.problem_source} #{self.problem_number}'
class Topic(models.Model):
'''Model that represents the topic of a problem (e.g. Intermediate Combo)'''
problem_topic = models.CharField(max_length=50)
problem_level = models.CharField(max_length=15)
def __str__(self):
return f'{self.problem_level} {self.problem_topic}'
class Problem(models.Model):
'''Model that represents each problem (e.g. AIME #1, AMC #11, etc.)'''
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
source = models.OneToOneField(Source, on_delete=models.RESTRICT, null=True, unique=True)
problem_text = models.TextField()
topic = models.ManyToManyField(Topic)
def __str__(self):
"""String for representing the Model object."""
return f'{self.source}'
def get_absolute_url(self):
"""Returns the url to access a detail record for this book."""
return reverse('problem-detail', args=[str(self.id)])
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('problems/', views.ProblemListView.as_view(), name='problems'),
path('problem/<int:pk>', views.ProblemListView.as_view(), name='problem-detail'),
]
views.py
import imp
from django.shortcuts import render
# Create your views here.
from .models import Problem, Source, Topic
def index(request):
'''View function for home page of site'''
# generate counts of the main objects
num_problems = Problem.objects.all().count()
context = {
'num_problems': num_problems,
}
return render(request, 'index.html', context=context)
from django.views import generic
class ProblemListView(generic.ListView):
model = Problem
class ProblemDetailView(generic.DetailView):
model = Problem
我的 HTML 文件的链接如下:
base_generic.html: link
problem_list.html: link
problem_detail.html: link
我的工作区结构如下:
trivial
catalog
migrations
static/css
styles.css
templates
catalog
problem_detail.html
problem_list.html
base_generic.html
index.html
__init.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
trivial
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
我已阅读其他 Whosebug 帖子,但 none 似乎适用于我的情况。此外,在 problem_list.html 中,如果 href
link 中的值为 Problem.get_absolute_url
,站点将加载,但单击“所有问题”的 link 将返回同一页面。但是,如果我将 prob.get_absolute_url
放在 href
link 中,我会收到 NoReverseMatch 错误。
这是我得到的确切错误:
NoReverseMatch at /catalog/problems/
Reverse for 'problem-detail' with arguments '('41b936f7-3c08-4fb9-a090-2d466348d34d',)' not found. 1 pattern(s) tried: ['catalog/problem/(?P<pk>[0-9]+)\Z']
Request Method: GET
Request URL: http://127.0.0.1:8000/catalog/problems/
Django Version: 4.0.2
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'problem-detail' with arguments '('41b936f7-3c08-4fb9-a090-2d466348d34d',)' not found. 1 pattern(s) tried: ['catalog/problem/(?P<pk>[0-9]+)\Z']
Django 告诉我错误源于在 problem_list.html
prob.get_absolute_url
问题是 Problem
模型上的 id
是 UUID
,但 URL 模型需要一个整数值作为 pk
- 因为您已在命名模式前加上 int:
:
path('problem/<int:pk>', views.ProblemListView.as_view(), name='problem-detail'),
如果您将其更改为:
,它应该可以工作path('problem/<uuid:pk>', views.ProblemListView.as_view(), name='problem-detail'),