├── .gitignore ├── django_auth_example ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py ├── templates ├── index.html ├── registration │ ├── login.html │ ├── password_change_done.html │ ├── password_change_form.html │ ├── password_reset_complete.html │ ├── password_reset_confirm.html │ ├── password_reset_done.html │ └── password_reset_form.html └── users │ └── register.html └── users ├── __init__.py ├── admin.py ├── apps.py ├── backends.py ├── forms.py ├── migrations ├── 0001_initial.py └── __init__.py ├── models.py ├── tests.py ├── urls.py └── views.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | db.sqlite3 -------------------------------------------------------------------------------- /django_auth_example/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jukanntenn/django-auth-example/9e26bd6ae77a729349faa02bab110b1540334916/django_auth_example/__init__.py -------------------------------------------------------------------------------- /django_auth_example/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for django_auth_example project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.11.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.11/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | # Quick-start development settings - unsuitable for production 19 | # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ 20 | 21 | # SECURITY WARNING: keep the secret key used in production secret! 22 | SECRET_KEY = 'e_d-*d^al%=cx5y-a-og2tu@uhy@l*uwqmtc%y&@fhlblr' 23 | 24 | # SECURITY WARNING: don't run with debug turned on in production! 25 | DEBUG = True 26 | 27 | ALLOWED_HOSTS = [] 28 | 29 | # Application definition 30 | 31 | INSTALLED_APPS = [ 32 | 'django.contrib.admin', 33 | 'django.contrib.auth', 34 | 'django.contrib.contenttypes', 35 | 'django.contrib.sessions', 36 | 'django.contrib.messages', 37 | 'django.contrib.staticfiles', 38 | 'users', 39 | ] 40 | 41 | MIDDLEWARE = [ 42 | 'django.middleware.security.SecurityMiddleware', 43 | 'django.contrib.sessions.middleware.SessionMiddleware', 44 | 'django.middleware.common.CommonMiddleware', 45 | 'django.middleware.csrf.CsrfViewMiddleware', 46 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 47 | 'django.contrib.messages.middleware.MessageMiddleware', 48 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 49 | ] 50 | 51 | ROOT_URLCONF = 'django_auth_example.urls' 52 | 53 | TEMPLATES = [ 54 | { 55 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 56 | 'DIRS': [os.path.join(BASE_DIR, 'templates')], 57 | 'APP_DIRS': True, 58 | 'OPTIONS': { 59 | 'context_processors': [ 60 | 'django.template.context_processors.debug', 61 | 'django.template.context_processors.request', 62 | 'django.contrib.auth.context_processors.auth', 63 | 'django.contrib.messages.context_processors.messages', 64 | ], 65 | }, 66 | }, 67 | ] 68 | 69 | WSGI_APPLICATION = 'django_auth_example.wsgi.application' 70 | 71 | # Database 72 | # https://docs.djangoproject.com/en/1.11/ref/settings/#databases 73 | 74 | DATABASES = { 75 | 'default': { 76 | 'ENGINE': 'django.db.backends.sqlite3', 77 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 78 | } 79 | } 80 | 81 | # Password validation 82 | # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators 83 | 84 | AUTH_PASSWORD_VALIDATORS = [ 85 | { 86 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 87 | }, 88 | { 89 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 90 | }, 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 96 | }, 97 | ] 98 | 99 | # Internationalization 100 | # https://docs.djangoproject.com/en/1.11/topics/i18n/ 101 | 102 | LANGUAGE_CODE = 'zh-hans' 103 | 104 | TIME_ZONE = 'Asia/Shanghai' 105 | 106 | USE_I18N = True 107 | 108 | USE_L10N = True 109 | 110 | USE_TZ = True 111 | 112 | # Static files (CSS, JavaScript, Images) 113 | # https://docs.djangoproject.com/en/1.11/howto/static-files/ 114 | 115 | STATIC_URL = '/static/' 116 | 117 | AUTH_USER_MODEL = 'users.User' 118 | AUTHENTICATION_BACKENDS = ( 119 | 'django.contrib.auth.backends.ModelBackend', 120 | 'users.backends.EmailBackend', 121 | ) 122 | LOGOUT_REDIRECT_URL = '/' 123 | LOGIN_REDIRECT_URL = '/' 124 | 125 | EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' 126 | -------------------------------------------------------------------------------- /django_auth_example/urls.py: -------------------------------------------------------------------------------- 1 | """django_auth_example URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.11/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url, include 17 | from django.contrib import admin 18 | 19 | from users import views 20 | 21 | urlpatterns = [ 22 | url(r'^admin/', admin.site.urls), 23 | # 别忘记在顶部引入 include 函数 24 | url(r'^users/', include('users.urls')), 25 | url(r'^users/', include('django.contrib.auth.urls')), 26 | url(r'^$', views.index, name='index') 27 | ] 28 | -------------------------------------------------------------------------------- /django_auth_example/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for django_auth_example project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_auth_example.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_auth_example.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError: 10 | # The above import may fail for some other reason. Ensure that the 11 | # issue is really that Django is missing to avoid masking other 12 | # exceptions on Python 2. 13 | try: 14 | import django 15 | except ImportError: 16 | raise ImportError( 17 | "Couldn't import Django. Are you sure it's installed and " 18 | "available on your PYTHONPATH environment variable? Did you " 19 | "forget to activate a virtual environment?" 20 | ) 21 | raise 22 | execute_from_command_line(sys.argv) 23 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 首页 8 | 9 | 10 | 11 |
12 |
13 |
14 |

Django Auth Example

15 | {% if user.is_authenticated %} 16 |

你已登录,欢迎你:{{ user.username }}

17 | 19 | 21 | {% else %} 22 |

你还没有登录,请 23 | 25 | 或者 26 | 28 |

29 | {% endif %} 30 |
31 |
32 |
33 | 34 | -------------------------------------------------------------------------------- /templates/registration/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 登录 8 | 9 | 14 | 15 | 16 |
17 |
18 |
19 |
20 |

Django Auth Example

21 |

登录

22 |
23 | {% csrf_token %} 24 | {{ form.non_field_errors }} 25 | {% for field in form %} 26 | {{ field.label_tag }} 27 | {{ field }} 28 | {{ field.errors }} 29 | {% if field.help_text %} 30 |

{{ field.help_text|safe }}

31 | {% endif %} 32 | {% endfor %} 33 | 34 | 35 |
36 |
37 |
没有账号?立即注册
38 | 39 |
40 |
41 |
42 |
43 |
44 | 45 | -------------------------------------------------------------------------------- /templates/registration/password_change_done.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 密码修改成功 8 | 9 | 10 | 11 |
12 |
13 |
14 |

Django Auth Example

15 |

密码修改成功!

16 |
17 |
18 |
19 | 20 | -------------------------------------------------------------------------------- /templates/registration/password_change_form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 修改密码 8 | 9 | 14 | 15 | 16 |
17 |
18 |
19 |
20 |

Django Auth Example

21 |

修改密码

22 |
23 | {% csrf_token %} 24 | {{ form.non_field_errors }} 25 | {% for field in form %} 26 | {{ field.label_tag }} 27 | {{ field }} 28 | {{ field.errors }} 29 | {% if field.help_text %} 30 |

{{ field.help_text|safe }}

31 | {% endif %} 32 | {% endfor %} 33 | 34 |
35 |
36 |
37 |
38 |
39 | 40 | -------------------------------------------------------------------------------- /templates/registration/password_reset_complete.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 新密码设置成功 8 | 9 | 10 | 11 |
12 |
13 |
14 |

Django Auth Example

15 |

新密码设置成功

16 |

17 | 你的口令己经设置。现在你可以继续进行登录。 18 |

19 |
20 |
21 |
22 | 23 | -------------------------------------------------------------------------------- /templates/registration/password_reset_confirm.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 设置新密码 8 | 9 | 14 | 15 | 16 |
17 |
18 |
19 |
20 |

Django Auth Example

21 |

设置新密码

22 |
23 | {% csrf_token %} 24 | {{ form.non_field_errors }} 25 | {% for field in form %} 26 | {{ field.label_tag }} 27 | {{ field }} 28 | {{ field.errors }} 29 | {% if field.help_text %} 30 |

{{ field.help_text|safe }}

31 | {% endif %} 32 | {% endfor %} 33 | 34 |
35 |
36 |
37 |
38 |
39 | 40 | -------------------------------------------------------------------------------- /templates/registration/password_reset_done.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 密码重置链接已经发送 8 | 9 | 10 | 11 |
12 |
13 |
14 |

Django Auth Example

15 |

密码重置链接已经发送

16 |

17 | 如果您输入的邮件地址所对应的账户存在,设置密码的提示已经发送邮件给您,您将很快收到。 18 |

19 |

20 | 如果你没有收到邮件, 请确保您所输入的地址是正确的, 并检查您的垃圾邮件文件夹. 21 |

22 |
23 |
24 |
25 | 26 | -------------------------------------------------------------------------------- /templates/registration/password_reset_form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 重置密码 8 | 9 | 14 | 15 | 16 |
17 |
18 |
19 |
20 |

Django Auth Example

21 |

重置密码

22 |
23 | {% csrf_token %} 24 | {{ form.non_field_errors }} 25 | {% for field in form %} 26 | {{ field.label_tag }} 27 | {{ field }} 28 | {{ field.errors }} 29 | {% if field.help_text %} 30 |

{{ field.help_text|safe }}

31 | {% endif %} 32 | {% endfor %} 33 | 34 |
35 |
36 |
37 |
38 |
39 | 40 | -------------------------------------------------------------------------------- /templates/users/register.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 注册 8 | 9 | 14 | 15 | 16 |
17 |
18 |
19 |
20 |

Django Auth Example

21 |

注册

22 |
23 | {% csrf_token %} 24 | {% for field in form %} 25 | {{ field.label_tag }} 26 | {{ field }} 27 | {{ field.errors }} 28 | {% if field.help_text %} 29 |

{{ field.help_text|safe }}

30 | {% endif %} 31 | {% endfor %} 32 | 33 | 34 |
35 |
36 | 已有账号登录 37 |
38 |
39 |
40 |
41 |
42 | 43 | -------------------------------------------------------------------------------- /users/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jukanntenn/django-auth-example/9e26bd6ae77a729349faa02bab110b1540334916/users/__init__.py -------------------------------------------------------------------------------- /users/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import User 4 | 5 | admin.site.register(User) 6 | -------------------------------------------------------------------------------- /users/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class UsersConfig(AppConfig): 5 | name = 'users' 6 | -------------------------------------------------------------------------------- /users/backends.py: -------------------------------------------------------------------------------- 1 | from .models import User 2 | 3 | 4 | class EmailBackend(object): 5 | def authenticate(self, request, **credentials): 6 | email = credentials.get('email', credentials.get('username')) 7 | try: 8 | user = User.objects.get(email=email) 9 | except User.DoesNotExist: 10 | pass 11 | else: 12 | if user.check_password(credentials["password"]): 13 | return user 14 | 15 | def get_user(self, user_id): 16 | try: 17 | return User.objects.get(pk=user_id) 18 | except User.DoesNotExist: 19 | return None 20 | -------------------------------------------------------------------------------- /users/forms.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.forms import UserCreationForm 2 | 3 | from .models import User 4 | 5 | 6 | class RegisterForm(UserCreationForm): 7 | class Meta(UserCreationForm.Meta): 8 | model = User 9 | fields = ("username", "email") 10 | -------------------------------------------------------------------------------- /users/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.11.1 on 2017-05-19 06:31 3 | from __future__ import unicode_literals 4 | 5 | import django.contrib.auth.models 6 | import django.contrib.auth.validators 7 | from django.db import migrations, models 8 | import django.utils.timezone 9 | 10 | 11 | class Migration(migrations.Migration): 12 | 13 | initial = True 14 | 15 | dependencies = [ 16 | ('auth', '0008_alter_user_username_max_length'), 17 | ] 18 | 19 | operations = [ 20 | migrations.CreateModel( 21 | name='User', 22 | fields=[ 23 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 24 | ('password', models.CharField(max_length=128, verbose_name='password')), 25 | ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), 26 | ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), 27 | ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), 28 | ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), 29 | ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), 30 | ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), 31 | ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), 32 | ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), 33 | ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), 34 | ('nickname', models.CharField(blank=True, max_length=50)), 35 | ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), 36 | ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), 37 | ], 38 | options={ 39 | 'verbose_name': 'user', 40 | 'abstract': False, 41 | 'verbose_name_plural': 'users', 42 | }, 43 | managers=[ 44 | ('objects', django.contrib.auth.models.UserManager()), 45 | ], 46 | ), 47 | ] 48 | -------------------------------------------------------------------------------- /users/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jukanntenn/django-auth-example/9e26bd6ae77a729349faa02bab110b1540334916/users/migrations/__init__.py -------------------------------------------------------------------------------- /users/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.auth.models import AbstractUser 3 | 4 | 5 | class User(AbstractUser): 6 | nickname = models.CharField(max_length=50, blank=True) 7 | 8 | class Meta(AbstractUser.Meta): 9 | pass 10 | -------------------------------------------------------------------------------- /users/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /users/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | app_name = 'users' 6 | urlpatterns = [ 7 | url(r'^register/', views.register, name='register'), 8 | ] 9 | -------------------------------------------------------------------------------- /users/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, redirect 2 | 3 | from .forms import RegisterForm 4 | 5 | 6 | def register(request): 7 | # 从 get 或者 post 请求中获取 next 参数值 8 | # get 请求中,next 通过 url 传递,即 /?next=value 9 | # post 请求中,next 通过表单传递,即 10 | redirect_to = request.POST.get('next', request.GET.get('next', '')) 11 | 12 | # 只有当请求为 POST 时,才表示用户提交了注册信息 13 | if request.method == 'POST': 14 | # request.POST 是一个类字典数据结构,记录了用户提交的注册信息 15 | # 这里提交的就是用户名(username)、密码(password)、确认密码、邮箱(email) 16 | # 用这些数据实例化一个用户注册表单 17 | form = RegisterForm(request.POST) 18 | 19 | # 验证数据的合法性 20 | if form.is_valid(): 21 | # 如果提交数据合法,调用表单的 save 方法将用户数据保存到数据库 22 | form.save() 23 | 24 | if redirect_to: 25 | return redirect(redirect_to) 26 | else: 27 | return redirect('/') 28 | else: 29 | # 请求不是 POST,表明用户正在访问注册页面,展示一个空的注册表单给用户 30 | form = RegisterForm() 31 | 32 | # 渲染模板 33 | # 如果用户正在访问注册页面,则渲染的是一个空的注册表单 34 | # 如果用户通过表单提交注册信息,但是数据验证不合法,则渲染的是一个带有错误信息的表单 35 | # 将记录用户注册前页面的 redirect_to 传给模板,以维持 next 参数在整个注册流程中的传递 36 | return render(request, 'users/register.html', context={'form': form, 'next': redirect_to}) 37 | 38 | 39 | def index(request): 40 | return render(request, 'index.html') 41 | --------------------------------------------------------------------------------