[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 }) class Meta: unique_together = ('title', 'publisher') get_latest_by = '-upload_timestamp' def get_authors(self): return ', '.join([author.__str__() for author in self.authors.all()]) def __str__(self): return "Title: {} | Authors: {} | Price: {}".format( self.title, self.get_authors(), self.price )
urls.py
app_name = 'bookrepo' urlpatterns = [ path('product/<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 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="{{ item.get_absolute_url }}" class="btn btn-sm my-btn detail-btn"> <span><i class="fa fa-info-circle"></i></span>Book Details </a> </div> </div> {% endfor %} </div>
坦白地说,我对ug和基于类的视图了解不多。我只使用了基于函数的视图。而且,通过搜索互联网,我发现了这种“笨拙”的方式来获取详细信息页面的网址。
在html模板中,我尝试过这种方式:(获得了相同的结果)
<a href="{% url 'bookrepo:product' b.slug %}" class="btn btn-sm my-btn detail-btn">
我在models.py文件中有一个名为Book的模型。并且此模型具有一个用于显示书籍详细信息的字段,用于显示书籍的详细信息。home.html模板中显示书籍,而product.html模板中的书籍则显示......>
简单地做:
<a href="{% url 'product' b.slug %}" class="btn btn-sm my-btn detail-btn">