0

I am trying to make it so that if the user already exists then log in the user else return error message. I read the documentation and implemented it into my own project. I get error: "The view sign_in.views.sign_in didn't return an HttpResponse object. It returned None instead."

from django.shortcuts import render, redirect
from .forms import SignInForm
from django.contrib.auth import authenticate, login
from django.contrib import messages

def sign_in(request):
    if request.method == "POST":
        form = SignInForm(request.POST)
    else:
        form = SignInForm()

    username = request.POST.get("username")
    password = request.POST.get("password")

    user = authenticate(username=username, password=password)

    if user is not None:
        login(request, user)
        return redirect("boom-home")
        messages.success(request, f"Signed in as {user}")
    else:
        return messages.error(request, f"Failed to sign in as {user}.")

    context = {
        "form": form
    }

    return render(request, "sign_in/sign_in.html", context)

NOTE: usually this error is because people do not put "return" before the "render" method but I do put return.

Caleb
  • 55
  • 5
  • 1
    `return messages.error(request, f"Failed to sign in as {user}.")` This line is the cause of your error. – Abdul Aziz Barkat Mar 28 '21 at 16:01
  • 1
    Also your code flows very badly even if the request is not of the method POST you still try to get the values and authenticate anyway. – Abdul Aziz Barkat Mar 28 '21 at 16:03
  • Thank you so much!. Although that was not the problem. the problem was that in the "else" statement I put "return" before the messages.error() and you're not supposed to do that. – Caleb Mar 28 '21 at 16:04
  • so your saying I should move the code inside the "if request.method == 'POST' block"? (the code that checks if user is not None) – Caleb Mar 28 '21 at 16:07
  • @Caleb: you are also not using the form to validate and clean the data. You can work with `form.is_valid()` and `form.cleaned_data[''username]` to validate and retrieve data. – Willem Van Onsem Mar 28 '21 at 16:19

1 Answers1

0

I solved this problem by adding the following lines

In the following link you can see more about this problem

The view didn't return an HttpResponse object. It returned None instead

def sign_in(request):

    if request.method == "POST":
        form = SignInForm(request.POST)
        if form.is_valid():  <---Add (Example)
           return redirect('home')<---Add (Example)
    else:
        form = SignInForm()
Nimantha
  • 6,405
  • 6
  • 28
  • 69