Django使用ModelForm遇UnboundLocalError,无法获取表单变量怎么解决?
问题解决步骤
1. 修复表单类的初始化方法位置错误
你在forms.py里把__init__方法写在了Meta类内部,这是核心错误——导致表单无法正确初始化字段,直接引发验证失败。正确写法是将__init__放在RecipeInputForm类顶层,与Meta类同级:
from django import forms from .models import RecipeModel class RecipeInputForm(forms.ModelForm): class Meta: model = RecipeModel exclude = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['i_one'].initial = 0 self.fields['v_one'].initial = 0
2. 解决UnboundLocalError错误
cook_prediction仅在表单验证通过时才被定义,若表单无效,该变量不存在,后续访问就会报错。需要提前初始化变量:
from django.shortcuts import render from django.contrib.auth.decorators import login_required from . import forms @login_required def index(request): cook_prediction = None # 提前初始化变量,避免未定义报错 if request.method == 'POST': recipe_form = forms.RecipeInputForm(request.POST) if recipe_form.is_valid(): cook_prediction = recipe_form.cleaned_data print("表单验证通过,获取数据:", cook_prediction) else: print("Recipe form errors: ", recipe_form.errors) print("Recipe form is not valid!") else: recipe_form = forms.RecipeInputForm() # 补充返回响应逻辑(示例) return render(request, 'your_template.html', {'form': recipe_form, 'prediction': cook_prediction})
3. 额外验证检查
- 确保模板中表单提交方式为
POST,且包含{% csrf_token %}标签,否则会因CSRF验证失败导致表单无效。 - 检查前端输入内容:
i_one需输入整数(BigInteger类型),v_one需输入数字(整数或小数,Float类型)。
内容的提问来源于stack exchange,提问作者Broono
相关产品推荐
相关产品推荐

