django 错误:UnboundLocalError at /receptor/patient_form/ local variable 'username' referenced before assignment

eanckbw9  于 2023-03-24  发布在  Go
关注(0)|答案(1)|浏览(128)

下面的代码给出了错误:分配前引用的/receptible/patient_form/局部变量“用户名”中出现错误。UnboundLocalError异常值:
在赋值之前引用的局部变量“username”。
'

@login_required
def createPatient(request):
    form=PatientForm(request.POST, request.FILES)
    # try:
    if request.method == "POST":
            if form.is_valid():
            
                first_name = form.cleaned_data['first_name']
                last_name = form.cleaned_data['last_name']
                username = form.cleaned_data['username']
                email = form.cleaned_data['email']
                password = form.cleaned_data['password']
                address = form.cleaned_data['address']
                phone_number = form.cleaned_data['phone_number']
                dob = form.cleaned_data['dob']
                gender = form.cleaned_data['gender']
            
        
            user = CustomUser.objects.create_user(username=username, email=email,password=password, first_name=first_name, last_name=last_name,user_type=5)
            user.patients.address = address
            user.patients.phone_number = phone_number
            user.patients.dob=dob
            user.patients.gender=gender
            user.save()

我该如何解决这个问题?

plicqrtu

plicqrtu1#

如果form.is_valid()返回False,因为您使用username变量创建用户,则在赋值之前引用的局部变量'username'将出现错误。

@login_required
def createPatient(request):
    form=PatientForm(request.POST, request.FILES)
    # try:
    if request.method == "POST":
        if form.is_valid():
        
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            address = form.cleaned_data['address']
            phone_number = form.cleaned_data['phone_number']
            dob = form.cleaned_data['dob']
            gender = form.cleaned_data['gender']
        
    
            user = CustomUser.objects.create_user(username=username, email=email,password=password, first_name=first_name, last_name=last_name,user_type=5)
            user.patients.address = address
            user.patients.phone_number = phone_number
            user.patients.dob=dob
            user.patients.gender=gender
            user.save()
        else:
            # handle in case of form is not valid, i.e. form have some errors
    else:
        # handle in case of user send a GET request ( like raise error GET method not allowed)

相关问题