0

我正在尝试创建一个存储问题(特别是数学问题)并将其显示给用户的应用程序。我还没有添加很多我想要的功能,而且由于我对 Django 还很陌生,我一直在关注 Django 教程项目,并根据我的需要进行更改。但是,即使我似乎传入了正确的参数,我也遇到了 NoReverseMatch 错误。我的代码如下。

模型.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)])

网址.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'),
]

视图.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:链接 问题_list.html:链接问题 _detail.html
链接

我的工作区结构如下:

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

我已经阅读了其他 StackOverflow 帖子,但似乎没有一个适用于我的情况。此外,在 problem_list.html 中,如果href链接中的值为Problem.get_absolute_url,则站点将加载,但单击“所有问题”的链接将返回同一页面。但是,如果我prob.get_absolute_url输入href链接,我会收到 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告诉我错误源于prob.get_absolute_url调用problem_list.html

4

1 回答 1

0

问题是您idProblem模型上是 a 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'),
于 2022-02-25T05:23:58.190 回答