Django卡路里应用POST请求中带空格食物名称被截断问题求助
问题:带空格的食物名称提交后被截断
我正在开发一款卡路里应用,用户从下拉列表选择食物后,系统会将其添加到数据库的用户摄入食物列表中,最终统计总卡路里。目前表单功能已实现,但遇到异常:当食物名称包含空格时(例如“Egg, raw (147g)”),后端获取到的food_item_name会在空格处被截断,仅拿到“Egg,”;无空格的食物名称则正常。使用Django Admin界面操作时一切正常。
原HTML代码
<div class="container"> <form method="POST"> {% csrf_token %} <select class="form-control" id="food_consumed" name="food_consumed"> {% for item in items %} <option value={{item.item_name}}> {{item.item_name}} </option> {% endfor %} </select> <button type="submit" class="btn btn-success m-3"> Add </button> </form> </div>
原视图代码
def index(request): if request.method == "POST": food_item_name = request.POST.get('food_consumed') food_item = FoodModel.objects.filter(item_name = food_item_name) food_consumer = request.user food_item_consumed = Consumer(food_consumer = food_consumer, food_consumed = food_item) food_item_consumed.save() food_items = FoodModel.objects.all() return render(request, 'CaloriesApp/index.html', context={'items':food_items})
问题原因
- HTML属性值未加引号:
<option>的value直接写{{item.item_name}},当名称包含空格时,HTML会将空格视为属性值的结束标记,导致提交时仅传递空格前的部分。 - 视图查询逻辑问题:
filter()返回的是QuerySet集合,直接赋值给外键字段food_consumed会触发错误(外键需要单个模型实例)。
解决方案
1. 修复HTML的<option>属性值
给value属性添加双引号,确保完整的食物名称被作为属性值传递:
<div class="container"> <form method="POST"> {% csrf_token %} <select class="form-control" id="food_consumed" name="food_consumed"> {% for item in items %} <option value="{{item.item_name}}"> {{item.item_name}} </option> {% endfor %} </select> <button type="submit" class="btn btn-success m-3"> Add </button> </form> </div>
2. 修复视图的查询逻辑
使用get()获取单个模型实例(而非filter()的QuerySet),并添加异常处理避免食物不存在时报错:
def index(request): if request.method == "POST": food_item_name = request.POST.get('food_consumed') try: # 用get获取唯一匹配的食物实例 food_item = FoodModel.objects.get(item_name=food_item_name) except FoodModel.DoesNotExist: # 可选:添加错误提示逻辑 return render(request, 'CaloriesApp/index.html', { 'items': FoodModel.objects.all(), 'error': '所选食物不存在' }) food_consumer = request.user food_item_consumed = Consumer(food_consumer=food_consumer, food_consumed=food_item) food_item_consumed.save() food_items = FoodModel.objects.all() return render(request, 'CaloriesApp/index.html', context={'items': food_items})
内容的提问来源于stack exchange,提问作者usama hussain
相关产品推荐
相关产品推荐

