为什么我在分配之前就得到了引用错误本地变量'user_form'的信息

时间:2019-01-11 11:06:32

标签: django django-models django-forms django-templates django-views

在代码中,为什么会出现“分配前引用本地变量'user_form'”错误?

from django.shortcuts import render
from basic_app.forms import UserForm,UserProfileInfoForm

def index(request):
 return render(request,'basic_app/index.html')

def register(request):

 registered=False

 if request.method=="POST":
    user_form=UserForm(data=request.POST)
    profile_form=UserProfileInfoForm(data=request.POST)

    if user_form.is_valid() and profile_form.is_valid():
        user=user_form.save()
        user.set_password(user.password) #Hashing the password
        user.save()

        profile=profile_form.save(commit=False)
        profile.user=user #Sets up one to one relationship

        if 'profile_pic' in request.FILES:
            profile.profile_pic=request.FILES['profile_pic']

            profile.save()

            registered=True

        else:

            print(user_form.errors,profile_form.errors)


    else:
        user_form=UserForm()
        profile_form=UserProfileInfoForm()

return render(request,'basic_app/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered})

这是在views.py文件中。 一段时间以来一直停留在这个项目上。请帮忙吗?

2 个答案:

答案 0 :(得分:1)

第二个else块缩进得太远。将其移回一级。

答案 1 :(得分:0)

您有缩进问题。在此处检查已编辑的内容

from django.shortcuts import render
from basic_app.forms import UserForm, UserProfileInfoForm


def index(request):
    return render(request, 'basic_app/index.html')


def register(request):
    registered = False
    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)  # Hashing the password
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user  # Sets up one to one relationship

            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']
                profile.save()
                registered = True

            else:
                print(user_form.errors, profile_form.errors)



    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()
    return render(request, 'basic_app/registration.html',  {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})