【问题标题】:Removed model instances and error "NoReversematch"删除模型实例和错误“NoReversematch”
【发布时间】:2020-10-29 16:53:20
【问题描述】:

我遇到了类似于此帖子here 的错误消息。

但是,我只有在对我的 django 模型实例执行以下步骤后才收到此消息,尤其是在管理员中。

我有一个模型,称为“产品”。在管理员中,我创建了这个产品的几个实例,每个实例都有一个“id”字段。所以,我有 5 个产品,每个产品都有“id”、“1”、“2”、“3”、“4”和“5”。

我有一个显示所有“产品”列表的 html 模板,其中包含指向每个产品的 url 链接:

class Product(models.Model)
   ...
   def get_absolute_url(self):
        return reverse('catalog:product_detail',
                       args=[self.id, self.slug])

这是模板的那部分:

<a href="{{ product.get_absolute_url }}"> </a>

单击此 url 将进入产品详细信息视图,如下所示(在 views.py 中):

def product_detail(request, id, slug):
    product = get_object_or_404(Product,
                                id=id,
                                slug=slug)    

    return render(request,
                  'catalog/product/detail.html',
                  {'product': product,})

我还创建了一个上下文处理器,以跟踪在context_processors.py 中本网站的所有模板中创建的产品。

现在,当我在 admin 中删除前几个产品(产品“1”、“2”、“3”),同时在 admin 中创建新产品(添加“6”、“7”, “8”和“9”),当我重新渲染模板时,我得到了这个“NoReverseMatch”错误。

我猜测,由于产品在管理员中被删除,但上下文过程仍保留该产品的记录,模板无法再找到反向 url。如何“重置”这种情况(即重置我的所有产品或上下文处理器)?

【问题讨论】:

  • 您有产品详情视图吗?将其添加到问题中。
  • @Arakkal Abu,我愿意。我已添加到问题中。

标签: django django-urls django-url-reverse


【解决方案1】:

我猜你有一个名为 catalog 的应用程序,你在其中定义了 Product 模型

我认为,您甚至不需要id,因为slug 显然必须是unique(在Product 模型中)

class Product(models.Model):
    """Model to store Products."""

    slug = models.SlugField(_('slug'), max_length=255,
        unique=True, null=True, blank=True,
        help_text=_(
            'If blank, the slug will be generated automatically '
            'from the given name.'
        )
    )


    name = models.CharField(_('name'), max_length=255,
        unique=True,
        help_text=_('The title of the product.')
    )

    [..]

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(Product, self).save(*args, **kwargs)

在你的函数中

def product_detail(request, slug):
    product = get_object_or_404(Product, slug=slug)

    return render(request,
                  'catalog/product/detail.html',
                  {'product': product,})

你可以像这样定义你的路线

app_name = 'catalog'
urlpatterns = [
..
    path('products/<slug:slug>', views.product_detail, name='product_detail'),
..
]

然后在您的模板中调用url

<a href="{% url 'catalog:product_detail' slug=product.slug %}"> </a>

【讨论】:

  • 感谢您的详细帮助。我刚刚完成了“白板”,对我的数据库进行了核对,重新创建了数据库并重新迁移。它解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 2010-10-15
  • 2021-08-01
  • 2013-01-07
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 2011-03-20
  • 2016-12-13
相关资源
最近更新 更多