我有一个books
应用程序,它使用一个UUID,包含所有书籍的列表视图和单个书籍的详细视图。我不断收到以下错误消息:
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
文件https://docs.djangoproject.com/en/2.2/topics/http/url/#路径-converters“rel=”nofollow noreferrer“/>将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 %}
标记中。使用其中一个,而不是两个。你知道吗或者:
或:
相关问题 更多 >
编程相关推荐