Django中基础if语句实现求助:根据腰围输入输出对应尺码
Hey there! Let's figure out how to get that waist size check working in Django. Since you didn't share your existing code, I'll cover the two most common approaches—handling the logic directly in your template, or processing it first in a view (which is usually the cleaner practice for separating business logic from presentation).
直接在Django模板中实现判断
If you want to handle the comparison right in your template, here's how to do it:
First, make sure the waist value is available in your template context (either passed from your view, or coming from a form instance). Then add this code to your template:
{% comment %} Convert waist to a number first if it's a string (e.g., from raw POST data) {% endcomment %} {% if waist|add:"0" < 100 %} <span>small</span> {% else %} <span>medium</span> {% endif %}
- Pro tip: If
waistcomes from a Django form field defined asIntegerFieldorFloatField, it'll already be a numeric type, so you can skip the|add:"0"filter and just comparewaist < 100directly. - The
|add:"0"filter safely converts string-based numbers to integers, preventing unexpected behavior from string comparisons (like "99" being treated as greater than "100" lexicographically).
在视图中处理逻辑后传递结果
For better separation of concerns (keeping templates focused on display, not logic), handle the check in your view first, then pass the result to the template:
View code (views.py):
from django.shortcuts import render def waist_check_view(request): result = "" if request.method == "POST": # Get the waist value from the submitted form waist_input = request.POST.get("waist", "") # Validate that the input is a number to avoid errors try: waist = float(waist_input) if waist < 100: result = "small" else: result = "medium" except ValueError: result = "Please enter a valid number for waist size" # Pass the result to your template return render(request, "your_template.html", {"result": result})
Template code (your_template.html):
<!-- Display the result from the view --> <p>{{ result }}</p>
This approach is better because it centralizes your logic in the view, making it easier to debug and modify later, and also adds validation to handle non-numeric inputs gracefully.
内容的提问来源于stack exchange,提问作者J.Kidd

