gpt4 book ai didi

python - 将 UUID 添加到我的 Django 应用程序会产生 NoReverseMatch 错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:19:00 25 4
gpt4 key购买 nike

我有一个使用 UUID 的 books 应用程序,其中包含所有书籍的 ListView 和个别书籍的详细 View 。我不断收到以下错误消息:

NoReverseMatch at /books/
Reverse for 'book_detail' with arguments '('/books/71fcfae7-bf2d-41b0-abc8-c6773930a44c',)' not found. 1 pattern(s) tried: ['books/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$']

这是 models.py 文件:

# books/models.py
import uuid
from django.db import models
from django.urls import reverse


class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
price = models.DecimalField(max_digits=6, decimal_places=2)

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('book_detail', args=[str(self.id)])

我正在使用的 urls.py 文件 id 从模型转换为 uuid

 # books/urls.py
from django.urls import path

from .views import BookListView, BookDetailView

urlpatterns = [
path('', BookListView.as_view(), name='book_list'),
path('<uuid:pk>', BookDetailView.as_view(), name='book_detail'),
]

顶级 urls.py 文件如下所示,并添加了一个 books/ 路由。

# urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('books/', include('books.urls')),

views.py 文件:

from django.views.generic import ListView, DetailView
from .models import Book

class BookListView(ListView):
model = Book
context_object_name = 'book_list'
template_name = 'books/book_list.html'

class BookDetailView(DetailView):
model = Book
context_object_name = 'book'
template_name = 'books/book_detail.html'

以及相关的模板文件。

<!-- templates/book_detail.html -->
{% extends '_base.html' %}

{% block content %}
{% for book in book_list %}
<div>
<h2><a href="{% url 'book_detail' book.get_absolute_url %}">{{ book.title }}</a></h2>
</div>
{% endfor %}
{% endblock content %}

我相信我正确地实现了这一点,但 URL 不喜欢我的 UUID。有什么不对?

最佳答案

问题不是“添加 uuid”。问题是您进行了两次 URL 反转:一次在 get_absolute_url 中,一次在 {% url %} 标记中。使用其中之一,而不是两者。

或者:

<a href="{% url 'book_detail' book.pk %}">{{ book.title }}</a>

或者:

<a href="{{ book.get_absolute_url }}">{{ book.title }}</a>

关于python - 将 UUID 添加到我的 Django 应用程序会产生 NoReverseMatch 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com