Django 3.0: Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P<slug>[^/]+)/$']

亡梦爱人 提交于 2021-02-11 15:59:40

问题


I have model named Book in models.py file. And this model has slug field to display details of books Books are being displayed in home.html template and product.html template is to display details of selected book.

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.

In html template, I tried this way to: (got the same results)

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

回答1:


Simply do:

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

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

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

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

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



来源:https://stackoverflow.com/questions/61692157/django-3-0-reverse-for-product-with-no-arguments-not-found-1-patterns-trie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!