首页 > 解决方案 > UnboundLocalError at / local variable 'Profile' 在赋值之前引用

问题描述

我正在写一个 django 视图,如图所示:-

def feed(request):
if request.user.is_authenticated:
    user=request.user
    profile=Profile.objects.filter(user=user)
    userfollowing=FollowingProfiles.objects.filter(Profile=profile)
    for following in userfollowing:
        username=following.ProfileName
        useraccount=User.objects.filter(username=username)
        Profile=Profile.objects.filter(user=useraccount)
        Post=post.objects.filter(Profile=Profile)
        comment=comment.objects.filter(post=Post)
        final_post_queryset=final_post_queryset+Post
        final_comment_queryset=final_comment_queryset+comment
    return render(request,'feed/feed.html',{'final_comment_queryset':final_comment_queryset,'final_post_queryset':final_post_queryset})
else:
    redirect('signup')

而模板 feed.html 是:-

{% extends 'base.html' %}
{% block content %}
{% load static %}

{% for p in final_post_queryset %}
   {{ p.DatePosted }}
   <img src="{{ p.Picture.url }}"/>
{% endblock %}

而错误是:-

所以错误在第三行

profile=Profile.objects.filter(user=user)

标签: pythondjangodjango-modelsdjango-views

解决方案


我假设你已经导入了Profile模块(withfrom .models import Profile或类似的),并且对它为什么不存在感到困惑(如果你没有,你需要将该导入添加到文件的顶部)。

即使您已导入它,此代码也不起作用。您的问题是您在函数范围内分配了名称Profile,使其成为局部变量,并且局部变量从函数的开头是局部的(但最初为空)。在将它们分配给它们之前尝试访问它们会引发UnboundLocalError您所看到的(仅当您在分配给它之前尝试从本地名称读取时才会引发该错误;它不能仅仅通过导入失败而引发一个模块,它只会引发一个NameError)。Profile即使您确实导入了全局导入,也看不到它,因为在函数中,Profile必须是本地或全局的,不能同时是两者。

要解决此问题,请为您的局部变量选择一个不同的名称,以便全局Profile保持可访问性:

def feed(request):
    if request.user.is_authenticated:
        user=request.user
        profile=Profile.objects.filter(user=user)  # This line is fine!
        userfollowing=FollowingProfiles.objects.filter(Profile=profile)
        for following in userfollowing:
            username=following.ProfileName
            useraccount=User.objects.filter(username=username)
            # Use lowercase profile, not Profile
            # Profile=Profile.objects.filter(user=useraccount)  # This line was the problem!
            profile = Profile.objects.filter(user=useraccount)  # This line is the solution!
            Post = post.objects.filter(Profile=profile)  # Change to match new name
            ... rest of your code ...

你之前已经profile正确地使用了小写字母,而且似乎再也不需要它了,所以我只是重用了这个名字。


推荐阅读