django NoReverseMatch at / Reverse for 'product_detail' with keyword arguments '' slug ':'}'未找到

gopyfrb3  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(117)

型号

class Product(models.Model):
    total_quantity = models.IntegerField()
    availability = models.IntegerField()
    product_name = models.CharField(max_length=100)
    featured_image = models.CharField(max_length=100)
    price = models.IntegerField()
    discount = models.IntegerField()
    product_information = RichTextField()
    model_name = models.CharField(max_length=100)
    categories = models.ForeignKey(Category, on_delete=models.CASCADE)
    tags = models.CharField(max_length=100)
    description = RichTextField()
    section = models.ForeignKey(Section, on_delete=models.DO_NOTHING)
    slug = models.SlugField(default='', max_length=500, null=True, blank=True)

    def __str__(self) :
        return self.product_name
    
    def get_absolute_url(self):
        from django.urls import reverse
        return reverse("product_detail", kwargs={'slug': self.slug})

    class Meta:
        db_table = "core_Product"

def create_slug(instance, new_slug=None):
    slug = slugify(instance.product_name)
    if new_slug is not None:
        slug = new_slug
    qs = Product.objects.filter(slug=slug).order_by('-id')
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s" % (slug, qs.first().id)
        return create_slug(instance, new_slug=new_slug)
    return slug

def pre_save_post_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)

pre_save.connect(pre_save_post_receiver, Product)

检视方式

def ProductDetail(request, slug):
    return render(request, 'product/product_detail.html')

HTML文件我没有添加完整的HTML代码

<div class="product-image w-img">
                                    <a href="{{i.get_absolute_url}}">
                                        <img src="{{ i.featured_image }}" alt="product" style="height: 280px;">
                                    </a>
                                </div>

模板呈现过程中出现错误,“product_detail”的关键字参数为“|”slug“:未找到“}”。已尝试1种模式:['product/(?P[-a-zA-Z0-9_]+)\Z ']
URL

path('product/<slug:slug>',ProductDetail, name='product_detail')

模板渲染出错,请帮我解决这个bug

v64noz0r

v64noz0r1#

请在“/”处检查您的视图/模板,因为错误来自那里。你必须在视图中有这样的东西:

reverse("product_detail", kwargs={'slug': something})

或类似的URL标签在模板一样

{% url 'product_detail' slug=something %}

其中something为空

相关问题