首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在赋值前引用的/局部变量“配置文件”的UnboundLocalError?

在赋值前引用的/局部变量“配置文件”的UnboundLocalError?
EN

Stack Overflow用户
提问于 2019-08-06 09:31:04
回答 1查看 463关注 0票数 0

如何解决UnboundLocalError at /profile/ local variable 'context' referenced before assignment这个问题。我看到一切都好起来了?当我删除Payment_method下拉菜单时,它可以工作,但是为什么它不使用下拉菜单呢?

models.py

代码语言:javascript
复制
Paymet_choices = (
    ('easypaisa','EasyPaisa Number'),
    ('jazzcash', 'Jazzcash Number'),
)
class Profile(models.Model):
    payment_method = models.CharField(max_length=6, choices=Paymet_choices)

forms.py

代码语言:javascript
复制
class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields  = ['image','Payment_method','Detail']

views.py

代码语言:javascript
复制
def profile(request):
    if request.method == 'POST': 
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

        context = {
            'u_form': u_form,
            'p_form': p_form
        }
    return render(request, 'users/profile.html', context)    
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-06 09:45:17

该错误意味着您在分配context变量之前使用它。

有两个问题。

首先,您的表单在这一行中无效:

if u_form.is_valid() and p_form.is_valid():

因此,它将继续执行下一行(这意味着在外部else语句之外):return render(request, 'users/profile.html', context),而您还没有为context变量赋值。

第二个问题,要解决这些错误,请检查您的缩进。

代码语言:javascript
复制
        context = {
            'u_form': u_form,
            'p_form': p_form
        }
    return render(request, 'users/profile.html', context)

它应该是

代码语言:javascript
复制
    context = {
        'u_form': u_form,
        'p_form': p_form
    }
    return render(request, 'users/profile.html', context)

它会解决这个错误,

现在,回到第一个问题,您的表单无效。

我们不知道为什么,直到您看到使用form.errors的错误。

将此添加到users/profile.html模板中的任何位置以检查错误

{{ form.non_field_errors }}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57373005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档