Django 3.0:反向查找"product",未找到任何参数.尝试了1种模式:['product/(?P< slug> [^/] +)/$'] [英] Django 3.0: Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P<slug>[^/]+)/$']

查看:66
本文介绍了Django 3.0:反向查找"product",未找到任何参数.尝试了1种模式:['product/(?P< slug> [^/] +)/$']的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在models.py文件中有一个名为Book的模型.该模型的字段很长,可以显示图书的详细信息书籍显示在home.html模板中,而product.html模板用于显示所选书籍的详细信息.

我对以及它们的工作原理了解不多.

I really don't know much about slugs, and how they work.

Models.py:

class Book(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField('Title', max_length=255)
    authors = models.ManyToManyField(Author, related_name='books_written')
    publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published')
    price = models.DecimalField('Price', decimal_places=2, max_digits=10)
    description = models.TextField('Description')
    upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True)
    categories = models.ManyToManyField(Category, related_name='book_category')
    cover = models.ImageField(upload_to='covers', null=True,blank=True)
    copyright_proof = models.ImageField(upload_to=book_copyrights_path, null=True,blank=True)
    slug = models.SlugField(max_length=100,blank=True)

    def get_absolute_url(self):
        return reverse("bookrepo:product", kwargs={
            'slug': self.slug
        })

    def __str__(self):
        return "Title: {} | Authors: {} | Price: {}".format(
            self.title, self.get_authors(), self.price
        )

urls.py

app_name = 'bookrepo'

urlpatterns = [
    path('product/<slug:slug>/', ItemDetailView.as_view(), name='product'),     
    path('',views.home,name='home'),
    path('about/',views.about,name='about'),
    path('faq/',views.faq,name='faq'),
    path('login/',views.user_login,name='login'),
    path('shop/',views.shop,name='shop'),
    path('signup/',views.registration,name='signup'),
    path('logout/', views.user_logout, name='logout'),
]

views.py

class ItemDetailView(DetailView):
    model = Book
    template_name = "bookrepo/product.html"
    def main(self, *args, **kwargs):
        # kwargs key should be equal to parameter passed from url
        slug_from_param = self.kwargs.get('slug')

def home(request):
    bookz = Book.objects.order_by('title')
    var = {'books': bookz, 'range': 10}
    return render(request, 'bookrepo/home.html', context=var)

home.html

<div class="row">
    {% load my_filters %}
        {% for b in books|slice:":10" %}
            <div class="col-lg-2 col-md-3 col-sm-4">
                <div class="item">
                    <img src="{{ b.cover.url }}" alt="book-image">
                    <h6>{{ b.title }}</h6>
                    <h6>{{ b.get_authors }}</h6>
                    <h6><span class="price">{{ b.price }}</span></h6>

                    <a href="{% url 'bookrepo:product' b.slug %}" class="btn btn-sm my-btn detail-btn">
                        <span><i class="fa fa-info-circle"></i></span>Book Details
                    </a>

                </div>
            </div>
        {% endfor %}
 </div>

老实说,我对和基于类的视图了解不多.我只使用了基于函数的视图.而且,通过搜索互联网,我发现了这种笨拙"的方式来获取详细信息页面的网址.

Honestly speaking, I don't know much about slugs and class-based views. I have used only function-based views. And, by searching internet, I found this "slug" way to get url of detail page.

在html模板中,我尝试过这种方式:(获得了相同的结果)

<a href="{{ item.get_absolute_url }}" class="btn btn-sm my-btn detail-btn">

推荐答案

只需这样做:

<a href="{% url 'product' b.slug %}" class="btn btn-sm my-btn detail-btn">

您的urls.py,< slug> < slug:slug> :

Your urls.py, <slug> to <slug:slug>:

path('product/<slug:slug>/', ItemDetailView.as_view(), name='product'), 

在您的views.py中,您可能会遇到如下问题:

In your views.py, you could get slug as:

class ItemDetailView(DetailView):
    model = Book
    template_name = "bookrepo/product.html"
    def main(self, *args, **kwargs):
        # kwargs key should be equal to parameter passed from url
        slug_from_param = self.kwargs.get('slug')

        # Your remaining codes

插入不过是网址.因为您不能在url中添加任何字符串,因为可以有空格,因此可以使用slug.看看参考

Slug is nothing but a url. As, you could not add any strings to url, as there can be spaces, you can use slug. Have a look at Refs

这篇关于Django 3.0:反向查找"product",未找到任何参数.尝试了1种模式:['product/(?P&lt; slug&gt; [^/] +)/$']的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆