我在models.py文件中有一个名为Book的模型。 这个模型有一个塞子字段来显示书籍的详细信息 书籍将显示在home.html模板中,而product.html模板将显示所选书籍的详细信息。
我对以及它们的工作原理了解不多。
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>
老实说,我对和基于类的视图了解不多。我只使用了基于函数的视图。而且,通过搜索互联网,我发现了这种“笨拙”的方式来获取详细信息页面的网址。
在html模板中,我尝试过这种方式:(获得相同的结果)
<a href="{{ item.get_absolute_url }}" class="btn btn-sm my-btn detail-btn">
只需做:
Your urls.py,
<slug>
to<slug:slug>
:在您的views.py中,您可能会遇到如下问题:
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