It’s because Python takes the block by indentation.
Note that your return render
is "on the same vertical line" as the if request.method == 'POST'
.
This will make your method add_user
only return the render
or HttpResponse
if the method is POST
In addition there is another passage that seems to be a mistake, which is the else
. It seems to me the intention was to leave the form = UserForm()
empty only if it wasn’t a POST request.
the most approximate correction in your case is the following code:
def add_user(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("Usuário criado com sucesso")
else:
form = UserForm()
return render(request, 'accounts/add_user.html', {'form' : form})
In the case of its validation if the form is valid, it makes no sense not to have a else
, then I would add one more:
def add_user(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("Usuário criado com sucesso")
else:
# Redirecione ou mostre uma mensagem de erro aqui
else:
form = UserForm()
return render(request, 'accounts/add_user.html', {'form' : form})
Welcome, first edit your question by pasting the code, not the print. The way the question is we can hardly help
– Pedro Augusto
Thank you! I am without the source code at the moment as I am not on my private computer. As soon as possible, I update the post.
– duardoalmeida