django中具有反向功能的错误。无法匹配模式

问题描述 投票:0回答:2

我正在使用Django创建我的第一个网站。在创建表单并将网站返回到刚刚创建的页面的详细信息页面时,我在/ books / books / add /中遇到了此NoReverseMatch问题找不到带有关键字参数'{'pk':39}'的'detail'。尝试了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)
python django django-urls django-url-reverse
2个回答
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

0
投票

更改此方法的来源:

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>,而不是pk

© www.soinside.com 2019 - 2024. All rights reserved.