【发布时间】:2020-05-31 13:25:19
【问题描述】:
我正在尝试测试具有slug 字段的应用程序模型Book 之一。我有一个自定义保存功能,如下所示。
models.py
class Book(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)
def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(self.title, allow_unicode=True)
return super(Book, self).save(*args, **kwargs)
为了对此进行测试,我创建了以下 test.py
class BookModelTests(TestCase):
@classmethod
def setUpTestData(cls):
Book.objects.create(title="Book One")
def test_get_absolute_url(self):
book = Book.objects.get(pk=1)
self.assertEquals(book.get_absolute_url(), '/books/book-one/')
但是当我运行测试时,它以django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$'].
失败
追溯
Traceback (most recent call last):
File "Bookman/bookman/bms/tests/test_models.py", line 14, in test_get_absolute_url
self.assertEquals(book.get_absolute_url(), '/books/book-one/')
File "Bookman/bookman/bms/models.py", line 26, in get_absolute_url
return reverse('book-detail', args=[str(self.slug)])
File "Bookman/venv/lib/python3.8/site-packages/django/urls/base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "Bookman/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 677, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$']
为什么slug 是空的?为什么不调用save 方法?我错过了什么?
【问题讨论】:
标签: django django-models django-testing