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.
– Developer
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.
– Developer
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)
– Developer
The code is extended if you don’t put it in the Pastebin, or any other repository so you can see.
– Edilson
I put the view in the question.
– Developer
And what would be the
else
there ? Have you usedif not defined_id
or evenif defined_id == None
? Why should everything return false when used with theif
, either None, False or Empty String.– Edilson
Else does not exist. If the address_id has value, I need to recover the address the same happens to the cliente_id.
– Developer
Okay, have you tried the examples I presented in this last comment ?
– Edilson
Let’s go continue this discussion in chat.
– Developer