我有一个“类别”,“子类别”和“产品”模型。与其查看每个类别,子类别和产品,不如我想浏览要使用righ模型填充的模板。
models.py
class Category(models.Model):
category_title = models.CharField(max_length=200)
category_image = models.ImageField(upload_to="category")
category_description = models.TextField()
category_slug = models.SlugField(max_length=200, default=1)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.category_title
class Subcategory(models.Model):
subcategory_title = models.CharField(max_length=200)
subcategory_image = models.ImageField()
subcategory_category = models.ForeignKey(
Category, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT)
class Meta:
verbose_name_plural = "Subcategories"
def __str__(self):
return self.subcategory_title
class Product(models.Model):
product_title = models.CharField(max_length=200)
product_image = models.ImageField()
product_base_price = models.DecimalField(max_digits=12, decimal_places=2)
product_addons = models.CharField(max_length=200, blank=True)
product_description = models.TextField()
product_date_added = models.DateTimeField(default=datetime.now, blank=True)
product_slug = models.SlugField(max_length=200, default=1)
product_subcategory = models.ForeignKey(
Subcategory, default=1, verbose_name="Subcategories", on_delete=models.SET_DEFAULT)
product_available = models.BooleanField(default=True)
答案 0 :(得分:0)
以下是产品模型的示例view
,url
和template
。请用您的应用名称替换myapp
。
定义视图:
# views.py
from django.views.generic import ListView
from django.shortcuts import render
from .models import Product
class ProductList(ListView):
model = Product
def productdetail(request,id):
product = Product.objects.get(id = id)
return render(request, 'myapp/product.html', {'product': product})
最后将该视图链接到您的网址中
# urls.py
from django.urls import path
from myapp.views import ProductList, productdetail
urlpatterns = [
path('products/', ProductList.as_view()),
path('products/<int:pk>/', productdetail, name='productdetail'),
]
创建一个模板,以列出以下位置的产品:/path/to/project/myapp/templates/myapp/products_list.html
{% extends "base.html" %}
{% block content %}
<h2>Products</h2>
<ul>
{% for product in object_list %}
<li><a href="{% url 'productdetail' product.id %}">{{ product.product_title }} </a></li>
{% endfor %}
</ul>
{% endblock %}
创建一个模板以显示特定的产品:/path/to/project/myapp/templates/myapp/product.html
::
{% extends "base.html" %}
{% block content %}
<h2>Product</h2>
{{product.product_title}}
{% endblock %}
答案 1 :(得分:0)
product_created_on = models.DateTimeField(auto_now_add=True)
我有答案,只需使用DateTimeField()