HTML模板上的Django过滤器函数
我被一个问题缠住了。我需要使用for循环中的list.id筛选所有列表。不幸的是,无法解析Django中的筛选器函数。是否有其他解决方案或解决方法?如何在Django HTML模板中运行函数。谢谢 index.htmlHTML模板上的Django过滤器函数,django,django-models,django-rest-framework,django-views,django-templates,Django,Django Models,Django Rest Framework,Django Views,Django Templates,我被一个问题缠住了。我需要使用for循环中的list.id筛选所有列表。不幸的是,无法解析Django中的筛选器函数。是否有其他解决方案或解决方法?如何在Django HTML模板中运行函数。谢谢 index.html {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> {% if not listing %} <h3>Nothing
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
{% if not listing %}
<h3>Nothing listed...</h3>
{% endif %}
{% for list in listing %}
<h3>Listing: {{ list.title }}</h3>
{% if list.photo != "" %}
<img src="{{ list.photo }}">
{% endif %}
<p>{{ list.description }}</p>
{% if not bids.filter(listing=list.id) %} #This line could not be parsed
<h5>${{ list.price }}</h5>
{% else %}
<h5>${{ bids.filter(listing=list.id).order_by(-bids).first().bids }}</h5> #This line could not be parsed
{% endif %}
<p>
{% if not bids.filter(listing=list.id).count() %} #This line could not be parsed
0
{% else %}
{{ bids.filter(listing=list.id).count() }} #This line could not be parsed
{% endif %}
bid(s) so far.
{% if bids.filter(listing=list.id).order_by(-bids).first().bidder == user.username %} #This line could not be parsed
Your bid is the current bid.
{% elif not bids.filter(listing=list.id).order_by(-bids).first().bidder %} #This line could not be parsed
There is no bid.
{% elif bids.filter(listing=list.id).order_by(-bids).first().bidder != user.username %} #This line could not be parsed
{{ bids.filter(listing=list.id).order_by(-bids).first().bidder }} is the current bid. #This line could not be parsed
{% endif %}
</p>
{% if user.username != list.user and user.is_authenticated %}
<form action="{% url "index" %} method="post">
{% for form in forms %}
{{ form }}
<input type="submit" value="Bid">
</form>
{% endfor %%}
{% endif %}
<h4>Details</h4>
<ul>
{% if user.username == list.user %}
<li>Listed by: You</li>
{% else %}
<li>Listed by: {{ list.user }}</li>
{% endif %}
<li>Category: {{ list.category }}</li>
</ul>
<hr>
{% endfor %}
{% endblock %}
型号.py
from .models import User, AuctionList, Bids, Comments
from .forms import AuctionForm, BidsForm
def index(request):
if request.method == "POST":
pass
else:
AL = AuctionList.objects.all()
Bd = Bids.objects.all()
forms = BidsForm()
return render(request, "auctions/index.html", {
"listing": AL.order_by("id"),
"bids": Bd,
"forms": forms
})
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class AuctionList(models.Model):
CATEGORY_CHOICES = [
('Books', 'Books'),
('Business & Industrial', 'Business & Industrial'),
('Clothing, Shoes & Accessories', 'Clothing, Shoes & Accessories'),
('Collectibles', 'Collectibles'),
('Consumer Electronics', 'Consumer Electronics'),
('Crafts', 'Crafts'),
('Dolls & Bears', 'Dolls & Bears'),
('Home & Garden', 'Home & Garden'),
('Motors', 'Motors'),
('Pet Supplies', 'Pet Supplies'),
('Sporting Goods', 'Sporting Goods'),
('Sports Mem, Cards & Fan Shop', 'Sports Mem, Cards & Fan Shop'),
('Toys & Hobbies', 'Toys & Hobbies'),
('Antiques', 'Antiques'),
('Computers/Tablets & Networking', 'Computers/Tablets & Networking')
]
id = models.AutoField(primary_key=True)
user = models.CharField(max_length=20, default='None')
title = models.CharField(max_length=20)
category = models.CharField(
max_length=30, choices=CATEGORY_CHOICES, default='Books')
description = models.TextField()
price = models.FloatField()
photo = models.URLField(max_length=200, blank=True)
def __str__(self):
return f"({self.id}) | Title: {self.title} | Category: {self.category} | Price: {self.price} | Posted by: {self.user}"
class Bids(models.Model):
bidder = models.CharField(max_length=20, default='None')
listing = models.ForeignKey(
AuctionList, on_delete=models.CASCADE, related_name="bids")
bids = models.FloatField()
def __str__(self):
return f"Listing Key: {self.listing} | Bids: {self.bids}"
答案是肯定的,您可以在html模板中运行过滤器函数。事实上,过滤函数适用于django模板中的任何地方,并且经常在django模板中使用,您可以在django中更准确地找到它,如 您还可以根据需要创建一个过滤器函数,并在模板中的任何位置使用它,即Django Templatetags。这些模板标记只不过是一种您自己定义并在模板中实现的函数。下面我将逐步向您解释: 对于reference,我的项目名称是“working\u blog\u python”,应用程序名称是“branch” 1。打开终端并键入
(working_blog_python) $ cd branch
(working_blog_python) $ mkdir templatetags
(working_blog_python) $ touch templatetags/any_name_tags.py
2。现在进入
any_name_tags.py
你可以这样写你的过滤函数
from django import template
register = template.Library()
@register.filter_function
def hrs(self):
return self.name.replace('-', ' ')
3。现在您可以在模板中的任何位置使用此hrs()
功能,但不要忘记在模板中加载{%load name\u tags%}
name\u标签
<p>Shop is located in {{branch.state | hrs | title}}.</p>
商店位于{{branch.state | hrs | title}}
您可以在views.py中创建另一个函数,并将其传递到索引函数中(下面的示例为您介绍views.py和index.html)
def build\u布局(用户名):
final_html=None
对于列表中的列表:
final_html='Listing:{}'。格式(list.title)
如果是list.photo:
final_html+='{}'.格式(list.description)
如果不是list.bids:#无法分析此行
最终html+='${}'。格式(list.price)
其他:
final_html+='${}.format(list.bids.order_by(-bids.first().bids)#无法分析此行
最终html+='{}到目前为止的出价'。格式(list.bids.count())
如果list.bids.order_by(-bids).first()。投标人==用户名:
final_html+=“您的出价是当前出价。”
其他:
final_html+=“没有出价。”
返回最终的html
def索引(请求):
如果request.method==“POST”:
通过
其他:
AL=AuctionList.objects.all()
Bd=Bids.objects.all()
表格=投标表格()
返回渲染(请求“auctions/index.html”{
“清单”:所有订单由(“id”),
“投标”:屋宇署,
“形式”:形式,
“拍卖布局”:构建拍卖布局(request.user.username)
})
#拍卖/index.html
{%extends“auctions/layout.html”%}
{%block body%}
出售中的物品
{%如果未列出%}
没有列出。。。
{%endif%}
{{拍卖|布局|安全}
......
def build_auctions_layout(username):
final_html = None
for list in listing:
final_html = '<h3>Listing: {}</h3>'.format(list.title)
if list.photo:
final_html += '<img src="{}"'.format(list.photo)
final_html += '<p>{}</p>'.format(list.description)
if not list.bids: #This line could not be parsed
final_html += '<h5>${}</h5>'.format(list.price)
else:
final_html += '<h5>${}</h5>'.format(list.bids.order_by(-bids).first().bids ) #This line could not be parsed
final_html += '<p>{} bid(s) so far'.format(list.bids.count())
if list.bids.order_by(-bids).first().bidder == username:
final_html += 'Your bid is the current bid.</p>'
else:
final_html += 'There is no bid.</p>'
return final_html
def index(request):
if request.method == "POST":
pass
else:
AL = AuctionList.objects.all()
Bd = Bids.objects.all()
forms = BidsForm()
return render(request, "auctions/index.html", {
"listing": AL.order_by("id"),
"bids": Bd,
"forms": forms,
"auctions_layout": build_auctions_layout(request.user.username)
})
#auctions/index.html
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
{% if not listing %}
<h3>Nothing listed...</h3>
{% endif %}
{{auctions_layout|safe}}
......