此市场电子商务应用程序中的views.py部分遇到了一些麻烦。
我想在my_products.html页面中显示属于每个供应商的“每个产品的产品类别”。我仅将一种类别分配给一种产品。但是我不确定views.py,my_products.html和urls.py中的这三行代码是否可以正常工作。
categories = Category.objects.get(name=request.name)
<td><a href="{% url 'shop:Edit_Product' product.category.category.name product.slug %}">{{ product.name }}</a></td>
path('edit_product/<slug:c_slug>/<slug:product_slug>/', views.EditProduct, name='Edit_Product'),
感谢我的Django知识,这是我正在学习的第三个月。
以下是更完整形式的代码:
my_products.html
<thead class="bg-success">
<tr>
<th>
<th>Product Title</th>
<th>Price ($)</th>
<th>Status</th>
</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{{ forloop.counter }}</td>
<td><a href="{% url 'shop:Edit_Product' product.category.category.name product.slug %}">{{ product.name }}</a></td>
<td>{{ product.price }}</td>
<td>{% if product.available %}Active {% else %} Disabled {% endif %}</td>
</tr>
{% endfor %}
</tbody>
edit_product.html
{% extends 'base.html' %}
{% load staticfiles %}
{% block title %}
Edit Your Cushion Collection - Perfect Cushion Store
{% endblock %}
{% block content %}
Edit Product page
{% endblock %}
views.py(商店应用)
@login_required(login_url="/")
def MyProducts(request):
products = Product.objects.filter(user=request.user)
categories = Category.objects.get(name=request.name???)
return render(request, 'shop/my_products.html', {'products':products}, {'categories':categories})
urls.py(商店应用)
app_name='shop'
urlpatterns = [
path('my_products/', views.MyProducts, name='My_Products'),
path('create_product/', views.CreateProduct, name='Create_Product'),
path('edit_product/<slug:c_slug>/<slug:product_slug>/', views.EditProduct, name='Edit_Product'),
]
models.py
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
def get_url(self):
return reverse('shop:products_by_category', args=[self.slug])
def __str__(self):
return '{}'.format(self.name)
class Product(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def get_url(self):
return reverse('shop:ProdCatDetail', args=[self.category.slug, self.slug])
def __str__(self):
return '{}'.format(self.name)