How to set Login Cookie/session?

Hi Guys,
I’m new to Django and trying to set a cookie while user perform login and credentials will be saved on the browser

Not sure what i’m missing, but my code does not create any cookie on the web browser

def login(request):
  template2 = loader.get_template("login.html")

  if request.COOKIES.get('uslgid'):
    return HttpResponse("Already Logged In")
  else:
    return HttpResponse(template2.render())
def auth(request):
  global dbuseridb
  if request.method=="GET":
     credentials =[request.GET.get('username'),request.GET.get('password')]
     mysqlconn = mysql.connector.connect(host="localhost", user="root", password="root", database='schema')  
     cursor = mysqlconn.cursor(buffered=True)
     query = " SELECT id FROM schema.users WHERE username=%s AND password=%s"
     cursor.execute(query,credentials)
    
     cursor.close()
     mysqlconn.close()

     for row in cursor:
      dbuseridb = row[0]

     if(dbuseridb):
      response = HttpResponse('Setting user login cookie')
      response.set_cookie('uslgid', username)
      return HttpResponse("logged in")
     else:
      return HttpResponse("Wrong username or password.")

Is there a reason why you’re trying to do it this way rather than using Django’s authentication system? (Or one of the third-party alternatives?)

Django provides a complete security infrastructure for doing things like this that are tested and proven secure and reliable. (See Using the Django authentication system | Django documentation | Django to get started.)

Also, you describe yourself as being “new to Django”. Have you worked your way through either the Official Django Tutorial or the Django Girls Tutorial? Those are great places to start to help you understand how all the different pieces of Django work together, allowing you to create web applications.

1 Like