Used to allow multiple users to register for a given application
- Create a new app called 'accounts'
python manage.py startapp accounts
-
Set up
templates
directory under'accounts'
, addlogin.html
&signup.html
pages -
Add
'accounts'
underINSTALLED_APPS
insettings.py
-
Create
forms.py
andurls.py
files for'accounts'
Complete login.html
and signup.html
templates
{% extends 'base.html' %}
{% load bootstrap3 %}
{% block title %}
Login / Signup
{% endblock %}
{% block content %}
<div class="container">
<h1>Login / Signup</h1>
<form method="POST">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Login" class="btn btn-primary">
</form>
</div>
{% endblock %}
from django.contrib.auth.models import User, PermissionsMixin
class SiteUser(User, PermissionsMixin):
def __str__(self):
return "@{}".format(self.username)
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
# UserCreationForm has built-in password validation
# https://docs.djangoproject.com/en/2.0/topics/auth/default/
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('username', 'email', 'password1', 'password2')
model = get_user_model()
def __init__(self, *args, **kwargs):
super(UserCreateForm, self).__init__(*args, **kwargs)
self.fields['username'].label = 'Display Name'
self.fields['email'].label = 'Email Address'
self.fields['password1'].label = 'Password'
self.fields['password2'].label = 'Verify Password'
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# LoginView and LogoutView are provided by django.contrib.auth
# https://docs.djangoproject.com/en/2.0/topics/auth/default/
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls', namespace='accounts')),
path('accounts/', include('django.contrib.auth.urls')),
]
from django.contrib.auth import views as auth_views
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
# LoginView and LogoutView are provided by django.contrib.auth
# https://docs.djangoproject.com/en/2.0/topics/auth/default/
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
# Create URL for signup page
path('signup/', views.SignUp.as_view(), name='signup'),
]
from django.contrib.auth import get_user_model
User = get_user_model()
class UserProfile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)