1

我正在使用 Django 创建我的第一个网站。在创建表单并将网站返回到刚刚创建的页面的详细信息页面时,我在 /books/books/add/ Reverse for 'detail' with keyword arguments '{'pk': 39}' not found 这个 NoReverseMatch 问题出现. 尝试了 1 种模式:['books/(?P[0-9]+)/$ 我已经尝试在我的 urls.py 文件中修复我的 URL,但是对于它来说是新手,我无法让它工作。

  urls.py file
from django.conf.urls import url
from django.contrib import admin
from . import views

app_name = 'books'
URL patterns = [
    url(r'^books/$', views.index, name='index'),
    url(r'^$', views.index, name='index'),
    url(r'^(?P<book_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'books/add/$',views.BookCreate.as_view(),name='book-add'),
]


model.py file 
from django.db import models

# Create your models here.
from django.core.urlresolvers import reverse


class Books(models.Model):

    def get_absolute_url(self):
        return reverse('books:detail', kwargs={"pk":self.pk})

    def __str__(self):
        return self.name + '-' + self.author

    name = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    price = models.CharField(max_length=100)
    book_image = models.CharField(max_length=1000)
4

2 回答 2

2

将此方法更改为:

def get_absolute_url(self):
    return reverse('books:detail', kwargs={"pk":self.pk})

至:

def get_absolute_url(self):
    return reverse('books:detail', kwargs={"book_id":self.pk})

因为您<book_id>在 urls 中使用,而不是pk.

于 2019-09-30T09:37:45.477 回答
0

您可以尝试像这样构造模型:

class Books(models.Model):
    name = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    price = models.CharField(max_length=100)
    book_image = models.CharField(max_length=1000)

    def get_absolute_url(self):
        return reverse('books:detail', kwargs={"pk":self.pk})

    def __str__(self):
        return self.name + '-' + self.author
于 2019-09-30T09:21:21.537 回答