Python, how to validate if the variable is None?

Asked

Viewed 2,013 times

1

I’m not able to verify if the variable has no value (None)

View:

endereco_id = request.POST.get('endereco_id', None)
if formCliente.is_valid() and formEndereco.is_valid():
    print('********** endereco_id **************')
    print(endereco_id)
    print('************************')
    if endereco_id:
       formEndereco.instance= Endereco.objects.get(id=endereco_id)

The print:

********** endereco_id **************
None
************************

Why is entering the IF if if in print the value of the variable is None?

Attempts:

if endereco_id != None:
     formEndereco.instance= Endereco.objects.get(id=endereco_id)

if endereco_id is not None: 
     formEndereco.instance= Endereco.objects.get(id=endereco_id)

Nothing worked, where am I wrong? The Python version is 3.5 with Django 1.10.

No Shell works:

>>> endereco_id=None
>>> if endereco_id:
...     print('Possui valor')
... else:
...     print('É None')
... 
É None
>>> endereco_id=1
>>> if endereco_id:
...     print('Possui valor')
... else:
...     print('É None')
... 
Possui valor
>>> 

View:

def novo_cliente(request):

    formCliente = ClienteForm(request.POST or None)
    formEndereco = EnderecoForm(request.POST or None)


    if request.method == 'POST':
        cliente_id = request.POST.get('cliente_id', None)
        endereco_id = request.POST.get('endereco_id', None)

        if formCliente.is_valid() and formEndereco.is_valid():
            if endereco_id is not None:
                formEndereco.instance= Endereco.objects.get(id=endereco_id)

            if cliente_id is not None:
                formCliente.instance= Cliente.objects.get(id=cliente_id)

            novo_endereco = formEndereco.save()
            novo_cliente = formCliente.save(commit=False)
            novo_cliente.endereco = novo_endereco
            novo_cliente.save()

            return redirect('appOrcamento:edit_cliente', orcamento.id)


    context = {
        'formCliente':formCliente,
        'formEndereco':formEndereco,
        }

    return render(request, 'appOrcamento/novo_cliente.html', context)
  • Edilson, thanks for the suggestion. Even though the variable is None, it entered Else.

  • Yes, I only included Else to test your suggestion. I really only have one line that should be processed if the address_id is different from None.

  • Edilson, I already tried with is not None, but I didn’t succeed. Even though the variable was None, it goes to if. I did the same test in the shell and it worked. Is the error because I am retrieving the POST value? address_id = request.POST.get('addresse_id', None)

  • The code is extended if you don’t put it in the Pastebin, or any other repository so you can see.

  • I put the view in the question.

  • And what would be the else there ? Have you used if not defined_id or even if defined_id == None ? Why should everything return false when used with the if, either None, False or Empty String.

  • Else does not exist. If the address_id has value, I need to recover the address the same happens to the cliente_id.

  • Okay, have you tried the examples I presented in this last comment ?

Show 4 more comments

1 answer

3


With help from @Edilson, we were able to identify the problem. It’s basic, but for those starting in Python with Django, it can become complicated. For this reason I will explain what happened.

When recovering the value of a field in the POST view, if the field does not exist in the template the return is None, that is, there is no field, it would be null. When the field exists in the template, but if it is without information the return in the post is a str 'None'.

That was my problem, in the print was being printed None, however it was of type str and if did not work properly.

Ex.:

cliente_id = request.POST.get('cliente_id', None)

If cliente_id does not exist in the template, the return will be None (null)

If cliente_id exists in the template, but without value, the return will be a str 'None'

The solution:

def novo_cliente(request):

    formCliente = ClienteForm(request.POST or None)
    formEndereco = EnderecoForm(request.POST or None)


    if request.method == 'POST':
        cliente_id = request.POST.get('cliente_id', None)
        endereco_id = request.POST.get('endereco_id', None)

        if formCliente.is_valid() and formEndereco.is_valid():
            if endereco_id != 'None':
                formEndereco.instance= Endereco.objects.get(id=endereco_id)

            if cliente_id != 'None':
                formCliente.instance= Cliente.objects.get(id=cliente_id)

            novo_endereco = formEndereco.save()
            novo_cliente = formCliente.save(commit=False)
            novo_cliente.endereco = novo_endereco
            novo_cliente.save()

            return redirect('appOrcamento:edit_cliente', orcamento.id)


    context = {
        'formCliente':formCliente,
        'formEndereco':formEndereco,
        }

    return render(request, 'appOrcamento/novo_cliente.html', context)

I hope this answer can help beginners.

@Edilson, thanks for your help.

  • 1

    Nice of you to work it out. Only read this now -check if you did not have a str with content "None" would be my suggestion - but it is a problem that can catch who has more years of home too. The tip you get when you have another similar mystery is to use the pdb - you put a break-point in the code with "import pdb; pdb.set_trace()" , submits the forumlarium, and accompanies in the Debugger the execution line to line - would have killed the problem in the first session also.

  • @jsbueno, blza? The pdb tip is excellent, I tried to use it, but when I had the processing followed it generated error. That was the hardness of the print. My colleague Edilson suggested the type(), that was the fly. We lost some time, but we did it. I put the answer to help people who are starting like me. Thanks for the comment, I will try to use pdb again. Now I assure you, problems with type of variables, never again...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.