NameError: name 'x' is not defined - Python - Django

0

I have a code that marks me an error of an undefined variable, but I do not know why.

This is my Model:

models.py

class Model(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    valor = models.FloatField(default=10)
    numero = models.FloatField(default=0)
    fecha = models.DateTimeField(auto_now_add=True, null=True)

What this code does is that when in the seconds of the current time it is stored in the variable n0the Model Model query, after accessing the number field and adding a value, it finally waits 10 seconds. In the same way when the seconds reach 50. ALL WELL UNTIL THE MOMENT

views.py

import time
from datetime import datetime

def actualizar(request):
    global n0, n1

    if datetime.now().second == 25:
        n0 = Model.objects.all().filter(user=request.user).first()
        n0.valor = n0.numero + 10
        time.sleep(10)

    if datetime.now().second == 50:
        n1 = Model.objects.all().filter(user=request.user).first()
        n1.valor = n1.numero + 20
        time.sleep(20)

    if x == 'activo':
        n0.numero = n0.valor * 1
        n1.numero = n1.valor * 2
        variable_nueva = n0.numero + n1.numero

This code is executed automatically by the time, but the problem appears with the following error:

n0.numero = n0.valor * 1
  

NameError: name 'n0' is not defined

The code works well but I do not know why it says it is not defined if it is stated globally, some friends, thank you very much !!!

And excuse my ignorance: (

    
asked by Yamamoto AY 30.08.2018 в 06:27
source

1 answer

1

The declaration of a global variable is discouraged because it can give future problems.

In your case, you are trying to declare a local variable with the word local in front and that is incorrect.

Since you are defining a variable within your method and consume it in the same method, you do not need to be global at all, likewise, if you decide to make them global, the reserved word local is used to be able to EDIT a previously defined global variable, but not to create them.

In your case, the code would look like this:

import time
from datetime import datetime

def actualizar(request):
    n0 = None
    n1 = None

    if datetime.now().second == 25:
        n0 = Model.objects.all().filter(user=request.user).first()
        n0.valor = n0.numero + 10
        time.sleep(10)

    if datetime.now().second == 50:
        n1 = Model.objects.all().filter(user=request.user).first()
        n1.valor = n1.numero + 20
        time.sleep(20)

    if x == 'activo':
        n0.numero = n0.valor * 1
        n1.numero = n1.valor * 2
        variable_nueva = n0.numero + n1.numero
    
answered by 30.08.2018 в 11:32