我正在尝试打印与特定客户有关的所有订单。我使用了for循环来访问html文件中的订单,并使用了if语句来确保订单与客户相关。
{% for order in orders %}
{% if customer.name == order %}
<a href="">{{ order }}</a>
{% endif %}
{% endfor %}
在我看来,我授予了html文件访问这些变量的权限。
def orderss(request, pk):
Customer = customer.objects.get(id=pk)
orders = Order.objects.all()
context = {
'customer':Customer,
'orders': orders,
}
return render(request, 'Inventory_Management/orders.html', context)
要访问此页面,我使用了一个按钮
<a href="{% url 'orderss' customer.id %}">View Orders</a>
网址是下面的网址
path('orders/<str:pk>/', orderss, name="orderss")
相关模型
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
order_head = models.ForeignKey(order_header, blank=False, null=True, on_delete=models.SET_NULL)
items = models.ForeignKey(item, blank=False, null=True, on_delete=models.SET_NULL)
Quantity = models.CharField(max_length=100)
date_created = models.DateTimeField(auto_now_add=True, null=True)
total = models.CharField(max_length=100)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return '{self.order_head.Buyer}'.format(self=self)
class customer(models.Model):
name = models.CharField(max_length=12, blank=False)
phone = models.CharField(max_length=12, blank=False)
email = models.CharField(max_length=50, blank=False)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class order_header(models.Model):
date_created = models.DateTimeField(auto_now_add=True, null=True)
User = models.CharField(max_length=100, blank=False, default="Seller")
Type = models.CharField(max_length=100, default="cash")
Buyer = models.ForeignKey(customer, blank=True, null=True, on_delete=models.SET_NULL)
Note = models.CharField(max_length=100, blank=True, default="Discount: ")
Order_Id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
def __str__(self):
return 'Order Customer: {self.Buyer}, Order Id: {self.Order_Id}'.format(self=self)
现在的问题是,当我按下按钮时没有订单显示,即使特定的客户有很多订单,我得到的还是空白页。帮助赞赏!请帮忙!
答案 0 :(得分:2)
在模板中,您尝试比较字符串name
与对象(Order
)的字段。我猜您认为使用name
方法会将order
与__str__
字符串表示形式进行比较。
尝试一下:
views.py
Customer = customer.objects.get(id=pk)
orders = order_header.objects.filter(Buyer=Customer)
context = {'orders': orders}
模板
{% for order_head in orders %}
{% for order in order_head.order_set.all %}
<a href="">{{ order }}</a>
{% endfor %}
{% endfor %}