如何将值传递给 Django 自定义模板标签的函数



在我的宠物项目中出现错误:

TemplateSyntaxError at /car/2/
'get_car_info' did not receive value(s) for the argument(s): 'car_id'

我可以看到,自定义模板标签中的函数不能接收值,但是Django日志显示car_id变量存在:

Local vars
Variable    Value
car_id      2
context     {'spare_parts': <QuerySet [<Mileage: Рулевой наконечник Sasic 7674007>]>,
'title': 'Список запчастей для'}
request     <WSGIRequest: GET '/car/2/'>

models.py

class Car(models.Model):
brand = models.CharField(max_length=40, db_index=True, verbose_name="Марка")
model_name = models.CharField(max_length=60, db_index=True, verbose_name="Модель")
model_variant = models.CharField(max_length=100, db_index=True, verbose_name="Модификация")
age = models.SmallIntegerField(verbose_name="Год выпуска")

views.py(注释代码移动到自定义模板标签)

def get_car_spare_parts(request, car_id):
spare_parts = Mileage.objects.filter(car_id=car_id)
# car = Car.objects.get(id=car_id)
context = {
'spare_parts': spare_parts,
'title': 'Список запчастей для',
# 'model_name': car.model_name,
# 'brand': car.brand,
# 'car_age': car.age,
}
return render(request, 'mileage/car.html', context)

urls . py

urlpatterns = [
path('car/<int:car_id>/', get_car_spare_parts, name='car_spare_parts'),]

mileage_tags.py

@register.simple_tag
def get_car_info(car_id):
car = get_object_or_404(Car, car_id=car_id)
return car

car.html

{% extends 'base.html' %}
{% load mileage_tags %}
{% block head %}
<title>{{ title }}</title>
{% endblock %}
{% block body %}
<h1>{{ title }} {{ brand }} {{ model_name }} {{ car_age }} г./в.</h1>
{% get_car_info %}
<ol class="list-group list-group-numbered">
{% for item in spare_parts %}
<li class="list-group-item"><a href="{% url 'spare_parts_mileages' item.car_id item.spare_part_id %}">{{ item }}</a></li>
{% endfor %}
</ol>
{% endblock %}

如何修复?

这里你可以在上下文中渲染汽车,而不是渲染每个字段,然后你可以像在上下文中一样访问模板中的字段。

def get_car_spare_parts(request, car_id):
spare_parts = Mileage.objects.filter(car_id=car_id)
car = Car.objects.get(id=car_id)
context = {
'spare_parts': spare_parts,
'title': 'Список запчастей для',
'car':car
}
return render(request, 'mileage/car.html', context)

然后在你的模板

{% extends 'base.html' %}
{% load mileage_tags %}
{% block head %}
<title>{{ title }}</title>
{% endblock %}
{% block body %}
<h1>{{ title }} {{ car.brand }} {{ car.model_name }} {{ car.age }} г./в.</h1>
{% get_car_info car.id %}
<ol class="list-group list-group-numbered">
{% for item in spare_parts %}
<li class="list-group-item"><a href="{% url 'spare_parts_mileages' item.car_id item.spare_part_id %}">{{ item }}</a></li>
{% endfor %}
</ol>
{% endblock %}
关于你的问题,你需要在模板标签中传递汽车id,就像这样
{% get_car_info car.id %}

相关内容

  • 没有找到相关文章

最新更新