如果 ID 已存在于其他表中,我会尝试隐藏按钮。 我的模板中有一个确认按钮,用于确认订单,并将确认的订单保存在名为 (ConfirmOrder) 的表中。所以我希望如果订单已确认或该订单的 ID 已存在于ConfirmOrder 表中,则确认按钮被禁用/隐藏,以便我无法再次确认。 我尝试使用 templatetags 时收到此错误(Unused 'v_item.pk' at end of if expression)
型号
class ConfirmOrder(models.Model):
order_no = models.ForeignKey(OrderDetail, related_name='confirmorders', on_delete = models.SET_NULL, null=True)
product = models.ForeignKey(StoreStock, null=True, blank=True, on_delete = models.SET_NULL)
quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)
buying_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)
amount = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)
confirm_note = models.CharField(max_length = 50, blank=True)
is_active = models.IntegerField(default=1)
模板标签
from django import template
from ..models import ConfirmOrder
register = template.Library()
@register.simple_tag
def check_item_already_exists(request, pk):
return ConfirmOrder.objects.filter(id=pk, is_active=1).exists()
模板
{% for v_item in viewitem %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ v_item.order_no.location }}</td>
<td>{{ v_item.order_no.order_date }}</td>
<td>{{ v_item.order_no.supplier }}</td>
<td>{{ v_item.order_no.order_number }}</td>
<td>{{ v_item.order_no.pay_ref }}</td>
<td>{{ v_item.product }}</td>
<td>{{ v_item.quantity }}</td>
<td>{{ v_item.buying_price }}</td>
<td>{{ v_item.amount }}</td>
<td>
{% load check_item %}
{% if not check_item_already_exists v_item.pk %}
<a class="btn btn-warning btn-sm" href="{% url 'confirm_order' v_item.pk %}"> Confirm </a>
{% endif %}
</td>
查看
def confirm_purchase(request):
viewitem = OrderItem.objects.all()
return render(request, 'managepurchase/confirmed_purchase.html', {'viewitem': viewitem})
我哪里做错了?或者还有其他方法可以做到这一点吗? 有谁可以帮忙吗!
最佳答案
请不要在模板中编写业务逻辑。模板处理渲染逻辑。不符合业务逻辑。 Django 模板语言被刻意限制,以避免人们在模板中编写大量业务逻辑。
在 View 中您可以.annotate(…)
[Django-doc] QuerySet
具有:
from django.db.models import Exists, OuterRef
def confirm_purchase(request):
viewitem = OrderItem.objects.annotate(
is_active=Exists(
<b>ConfirmOrder.objects.filter(is_active=1, pk=OuterRef('pk'))</b>
)
)
return render(request, 'managepurchase/confirmed_purchase.html', {'viewitem': viewitem})
然后在模板中我们可以使用以下方式渲染它:
{% if v_item<b>.is_active</b> %}
<a class="btn btn-warning btn-sm" href="{% url 'confirm_order' v_item.pk %}"> Confirm </a>
{% endif %}
关于Django:if 表达式末尾未使用 'v_item.pk',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62608999/