首页 > 解决方案 > django sessions remember me

问题描述

I am new to django and have not found a question corresponding to my entry level. And I just can't figure out how to work with sessions. I want to make a checkbox on login to remember me. After I registered in settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True, you need to enter your username and password after closing the browser. How do I change this parameter using the "remember me" checkbox? Thank you

 views.py
def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return redirect('/')
        else:
            messages.info(request, 'invalid credentials')
            return redirect('login')
    else:
        return render(request, 'prof/login.html')


login.html

<body>
  <div class="text-center mt-5">
    <form style="max-width: 480px; margin: auto" method="post">
      {% csrf_token %}
      <img
        src="https://logodix.com/logo/1713894.jpg"
        alt=""
        width="120"
        height="90"
        class="d-inline-block mt-4 mb-4"
      />
      <p class="hint-text mb-3">Please sign in</p>
      <label class="sr-only" for="username"></label>
      <input
        type="login"
        name="username"
        class="form-control"
        placeholder="username"
        required
        autofocus
      />
      <label for="password" class="sr-only"></label>
      <input
        type="password"
        name="password"
        class="form-control mt-2"
        placeholder="password"
      />
      <div class="checkbox">
        <label for="checkbox">
          <input type="checkbox" name="checkbox" value="remember-me" /> remember
          me
        </label>
      </div>
      <div class="d-grid gap-2 mt-4">
        <input type="Submit" class="btn btn-primary" value="sign in" />
      </div>
    </form>
    <div class="messages">
      {% for message in messages %}
      <h3>{{message}}</h3>
      {% endfor %}
    </div>

标签: pythondjangocheckbox

解决方案


def login(request):
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']
    user = auth.authenticate(username=username, password=password)
    try:
        remember = request.POST['remember_me']
        if remember:
            settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False
    except:
        is_private = False
        settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True

    if user is not None:
        auth.login(request, user)
        return redirect('/')
    else:
        messages.info(request, 'invalid credentials')
        return redirect('login')
else:
    return render(request, 'prof/login.html')

推荐阅读