Last active
October 6, 2019 02:52
-
-
Save ahankinson/7597778 to your computer and use it in GitHub Desktop.
Django Login
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.auth.views import logout | |
from django.contrib.auth import login | |
from django.shortcuts import render, redirect | |
from django.views.generic.base import View | |
from django.contrib.auth.forms import AuthenticationForm | |
class LoginFormView(View): | |
form_class = AuthenticationForm | |
template_name = 'login.html' | |
def get(self, request): | |
form = self.form_class() | |
return render(request, self.template_name, {'form': form}) | |
def post(self, request): | |
form = self.form_class(data=request.POST) | |
if form.is_valid(): | |
login(request, form.get_user()) | |
return redirect("/") | |
else: | |
return render(request, self.template_name, {'form': form}) | |
def logout_view(request): | |
""" | |
Logs out the current user. | |
""" | |
logout(request) | |
next = request.GET.get('next', None) | |
if next: | |
return redirect(next) | |
else: | |
return redirect('/') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% extends "base.html" %} | |
{% block wrap %} | |
{% if form.errors %} | |
<p>Your username and password didn't match. Please try again.</p> | |
{% endif %} | |
<form class="form-horizontal" method="post" action="/login"> | |
{% csrf_token %} | |
<div class="control-group"> | |
<label class="control-label" for="id_username"> | |
{{ form.username.label_tag }} | |
</label> | |
<div class="controls"> | |
{{ form.username }} | |
</div> | |
</div> | |
<div class="control-group"> | |
<label class="control-label" for="id_password"> | |
{{ form.password.label_tag }} | |
</label> | |
<div class="controls"> | |
{{ form.password }} | |
</div> | |
</div> | |
<div class="control-group"> | |
<div class="controls"> | |
<button type="submit" class="btn">Login</button> | |
<input type="hidden" name="next" value="{{ next }}" /> | |
</div> | |
</div> | |
</form> | |
{% endblock %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment