Search code examples
pythondjangoglobal-variablessmsverify

global variable not defined in django


I have a problem with this code in django I have defined two global variables

But Django does not identify them

my view:

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})

my urls :

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

i have this error :

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

I want the user to enter the site after entering the SMS code.


Solution

  • Caution: Global variables violates maybe the most important principle of the programming, the encapsulation. Using them, will turn your code to a spaghetti. Don't use them. (Unless there is another way)

    Here is what encapsulation means:

    ...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.

    Source: Wikipedia

    If you really want to use it, here is your problem: global keyword should be used in functions.

    Let's try that way:

    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":
        ...