django 中未定义全局变量

global variable not defined in django

我在 django 中遇到此代码的问题 我定义了两个全局变量

但 Django 不识别它们

我的看法:

global phone,rand_num
def phone_login(request):
    if request.method == 'POST':
        form = PhoneLoginForm(request.POST)
        if form.is_valid():
            phone = f"0{form.cleaned_data['phone']}"
            rand_num = randint(1000, 9999)
            api = KavenegarAPI('mytoken!')
            params = { 'sender' : '', 'receptor': phone , 'message' : rand_num }
            api.sms_send(params)
            return redirect('account:verify')

    else :
        form = PhoneLoginForm()
    return render(request,'account/phone_login.html',{'form':form})


def verify(request):
    if request.method == "POST":
        form = VerifyCodeForm(request.POST)
        if form.is_valid():
            if rand_num == form.cleaned_data['code']:
                profile = get_object_or_404(Profile, phone = phone)
                user = get_object_or_404(User,profile__id = profile.id)
                login(request,user)
                messages.success(request,'logged in successfully' , 'success')
                return redirect('popasssts:all_posts')
            else:
                messages.error(request,'your code is wrong','warning')
                
    else:
        form = VerifyCodeForm()
    return render(request,'account/verify.html',{'form' : form})

我的网址:

path('verify/',views.verify,name='verify'),

我有这个错误:

NameError at /account/verify/

name 'rand_num' is not defined

Request Method:     POST
Request URL:    http://127.0.0.1:8000/account/verify/
Django Version:     3.0.7
Exception Type:     NameError
Exception Value:    

name 'rand_num' is not defined

我想让用户在输入短信代码后进入网站。

注意: 全局变量可能违反了编程最重要的原则,即封装。使用它们,会将您的代码变成意大利面条。不要使用它们。 (除非有别的办法)

这里是封装的意思:

...Encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components.

来源:Wikipedia

如果你真的想使用它,这是你的问题:global 关键字应该在函数中使用。

我们试试看:

phone = ""
rand_num = 0

def phone_login(request):
    global phone, rand_num
    if request.method == 'POST':
    ...

def verify(request):
    global phone, rand_num
    if request.method == "POST":
    ...

关于全局变量,需要在函数内部加上global关键字,在外部给变量赋初值:

phone = ""
rand_num = -1

def phone_login(request):
    global phone, rand_num
    # ...

def verify(request):
    global phone, rand_num
    # ...

通过这种方法,phonerand_num 的值在应用程序的所有用户之间共享。如果您的应用程序有多个用户,更好的方法是将值存储在当前用户的会话中:

def phone_login(request):
    if request.method == 'POST':
        # ...

        if form.is_valid():
            # ...

            # Save the values in the session
            request.session["phone"] = phone
            request.session["rand_num"] = rand_num

            # ...


def verify(request):
    if request.method == "POST":
        # ...

        if form.is_valid():
            # Get the values from the session, setting
            # default values in case they don't exist.
            phone = request.session.get("phone", "")
            rand_num = request.session.get("rand_num", -1)

            # ...

要使用会话,必须在 Django 项目的 settings.py 文件的 INSTALLED_APPS 列表中启用 django.contrib.sessions 应用程序。此外,必须使用命令 python manage.py migrate.

将此应用程序迁移到项目的数据库

在官方Django documentation中您有更多关于会话的信息。