我正在Django中构建第一个应用程序,而条件循环遇到了麻烦。我想创建一个表单,用户可以在其中输入他们的姓名,家庭规模和收入,并根据收入来计算他们在浮动比例(A,B,C或超额合格)上的位置。我希望它能输出一个等级(A,B,C或超额合格),但它会不断循环播放-所以我得到的是:
如果有人因为我刚刚开始学习python和django而可以帮助我或指向我任何资源,那么我就很困了。
谢谢!
models.py
from django.db import models
# Create your models here.
class SlidingScale(models.Model):
scale = models.CharField(max_length=1)
family_size = models.IntegerField()
min_annual = models.IntegerField(default = 0)
max_annual = models.IntegerField()
def __str__(self):
return self.scale
forms.py
from django import forms
class SlidingForm(forms.Form):
name = forms.CharField(max_length = 100)
household = forms.IntegerField()
income = forms.IntegerField()
views.py
from django.shortcuts import render
from django.template.response import TemplateResponse
from .models import SlidingScale
from .forms import SlidingForm
# Create your views here. def index(request):
return render(request, 'index.html', {})
def calculator(request):
if request.method == "POST":
#Get the posted form
form = SlidingForm(request.POST)
data = SlidingScale.objects.all()
if form.is_valid():
name = form.cleaned_data['name']
household = form.cleaned_data['household']
income = form.cleaned_data['income']
else:
form = SlidingForm()
return render(request, 'result.html', {"name" : name, "household": household, "income":income, "data": data})
result.html
{% extends 'base.html' %}
<!--start title -->
{% block title%}
Result
{% endblock %}
<!-- start body -->
{% block content%}
<strong>{{ name }}</strong>, based on your income of <strong>{{income}}</strong> and household size of
<strong>{{household}}</strong>,
{% for i in data %}
{% if i.family_size == household and income >= i.min_annual and income <= i.max_annual %}
<p> You qualify for: {{ i.scale }} </p>
{% else %}
<p> You overqualify </p>
{% endif %}
{% endfor %}
{% endblock %}
答案 0 :(得分:0)
您根本不想在这里循环。您想从数据库中获取正确的项目。
if form.is_valid():
name = form.cleaned_data['name']
household = form.cleaned_data['household']
income = form.cleaned_data['income']
scale = SlidingScale.objects.filter(
family_size=household, min_annual__lte=income, max_annual__gte=income
).first()
return render(request, 'result.html',
{"name" : name, "household": household, "income":income, "scale": scale}
)
在模板中:
<strong>{{ name }}</strong>, based on your income of <strong>{{income}}</strong> and household size of
<strong>{{household}}</strong>,
{% if scale %}
<p> You qualify for: {{ scale.scale }} </p>
{% else %}
<p> You overqualify </p>
{% endif %}