参考 Django 文档:
https://docs.djangoproject.com/en/3.2/intro/tutorial03/#a-shortcut-render
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
为您的模型编辑
from django.shortcuts import render
from .models import VDSTARIFS
def vds(request):
ALL_VDSTARIFS = VDSTARIFS.objects.all()
FIRST_VDSTARIF = ALL_VDSTARIFS[:1]
# Get prise
prise = FIRST_VDSTARIF.prise
# Alternatives to print 'prise' in template
# Pass only the first item of vds list
context = {
"FIRST_VDSTARIF": FIRST_VDSTARIF
}
# Pass prise only
context = {
"prise": prise
}
# All records in html also the needed one in separated item
context = {
"ALL_VDSTARIFS": VDSTARIFS,
"FIRST_VDSTARIF": FIRST_VDSTARIF
}
return render(request, 'vds.html', context)
}
在模板中你可以使用 if
https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#if
{# Runs along all tarifs and print only one, not good. #}
{% for vdstarif in ALL_VDSTARIFS %}
{% if vdstarifs.id == "1" %}
{{ vdstarif.prise }}
{% endif %}
{% endfor %}
{# Only print the needed one #}
{{ FIRST_VDSTARIF.prise }}
{# Print prise #}
{{ prise }}
您可能会遵循 python 和 django 编码约定以及我的建议。
重命名 VDSTARIFS -> VdsTarif(查看您的管理页面,Django 在您的模型中添加“s”以使其复数)
为您的模型使用单数名称,并为 vdstarif_list 等视图中的变量名称添加后缀。
对于“prise”字段使用 DecimalField,看起来它是一个 CharField。是奖品还是价格?
https://docs.djangoproject.com/en/3.2/ref/models/fields/#decimalfield
from django.shortcuts import render
from .models import VdsTarif
def vds(request):
vdstarif_list = VdsTarif.objects.all()
context = {
"vdstarif_list" : vfstarif_list[:0].prise
}
return render(request, 'vds.html', context)