You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django视图报错:无法访问未赋值的局部变量'form'

问题解决:Django视图变量未赋值错误

错误原因

你的new_ingredient视图中,form变量仅在request.method == "POST"的代码块内定义。当请求为GET(比如首次访问页面)时,代码会跳过POST分支,直接执行context = {"recipe": recipe, "form": form},此时form没有被赋值,因此抛出cannot access local variable 'form' where it is not associated with a value错误。

修复方案

在POST分支之外初始化一个空的EntryForm实例,确保无论请求方法是什么,form变量都有值:

def new_ingredient(request, recipe_id):
    """Add a new entry for a particular recipe"""
    recipe = Recipe.objects.get(id=recipe_id)

    form = EntryForm()  # 初始化空表单
    if request.method == "POST":
        # POST data submitted; process data
        form = EntryForm(data=request.POST)
        if form.is_valid():
            new_ingredient = form.save(commit=False)
            new_ingredient.recipe = recipe  # 模型关联字段为recipe,而非owner
            new_ingredient.save()
            return redirect("recipe_book:recipe", recipe_id=recipe_id)

    # Display a blank or invalid form
    context = {"recipe": recipe, "form": form}
    return render(request, "recipe_book/new_ingredient.xhtml", context)

另外需要修正两处细节:

  • 模型Ingredient中关联Recipe的字段是recipe,但原视图里写的是new_ingredient.owner = recipe,字段不匹配需修正
  • 模型里的__str__方法缩进错误,它属于Ingredient类,而非Meta内部,修正后代码:
class Ingredient(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    text = models.TextField()
    time_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "ingredients"

    def __str__(self):
        return f"{self.text[:50]}..."

为什么之前正常?

大概率是之前仅测试了POST提交表单的场景,未触发GET请求加载空白页面的流程,或是后续修改代码时误删了初始化form的逻辑。

内容的提问来源于stack exchange,提问作者Ylli K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:01:09