第四章 在线教育平台(用户登录注册)

用户登录注册界面

标签: django


第四章 在线教育平台(用户登录注册)_第1张图片
登录

首页与登陆界面配置

复制主页及相关文件,其中包括静态文件。

 
urls

"""edu_gmooc URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
import xadmin

from users.views import user_login

urlpatterns = [
    url(r'^xadmin/', xadmin.site.urls),
    url('^$', TemplateView.as_view(template_name='index.html'), name='index'),
    url('^login/$', user_login, name='login'),
]


settings
# 自定义验证规则
AUTHENTICATION_BACKED = (
    'users.views.CustmerBacked',
)
# 静态文件
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
  • views
# _*_ encoding:utf-8 _*_
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from .models import UserProfile

# Create your views here.

#  邮箱验证规则
class CustmerBacked(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


def user_login(request):
    if request.method == 'POST':
        user_name = request.POST.get('username')
        pass_word = request.POST.get('password')
        user = authenticate(username=user_name, password=pass_word)
        if user is not None:
            login(request, user)
            return render(request, 'index.html')
        else:
            return render(request, 'login.html', {'msg': '用户名或密码错误!'})
    elif request.method == 'GET':
        return render(request, 'login.html')


  • index.html




    
    
    
    课程机构列表 - 慕学在线网
    
    
    
    
    
    



服务电话:33333333

{% if request.user.is_authenticated %}
bobby

django

bobby

{% else %} 注册 登录 {% endif %}
  • 专业权威

  • 课程最新

  • 名师授课

  • 数据真实

公开课程

名师授课
专业权威

查看更多课程 >

django入门

难度:初级 学习人数:3
慕课网 0

java入门

难度:中级 学习人数:0
北京大学 0

python入门

难度:中级 学习人数:0
南京大学 0

java入门2

难度:高级 学习人数:0
慕课网2 0

java入门3

难度:初级 学习人数:1
慕课网3 0

python入门2

难度:中级 学习人数:0
慕课网666 0
  • login.html




    
    
    
    慕学在线网登录
    
    


成功提交

您的需求提交成功!

邮件验证提示

我们已经向您的邮箱[email protected]发送了邮件,
为保证您的账号安全,请及时验证邮箱

去邮箱验证

没收到,您可以查看您的垃圾邮件和被过滤邮件,
也可以再次发送验证邮件

慕学在线网,在线学习平台!

类继承方式 实现url跳转

  • url
from users.views import LoginView

urlpatterns = [
    url(r'^xadmin/', xadmin.site.urls),
    url('^$', TemplateView.as_view(template_name='index.html'), name='index'),
    url('^login/$', LoginView.as_view(), name='login'),
]
  • views
class LoginView(View):

    def get(self, request):
        return render(request, 'login.html')

    def post(self,request):
        user_name = request.POST.get('username')
        pass_word = request.POST.get('password')
        user = authenticate(username=user_name, password=pass_word)
        if user is not None:
            login(request, user)
            return render(request, 'index.html')
        else:
            return render(request, 'login.html', {'msg': '用户名或密码错误!'})
  • from 表单验证
form

# _*_ encoding:utf-8 _*_

__author__ = 'wrj008'
__date__ = '2018/3/10 16:45'

from django import forms


class LoginForm(forms.Form):
    username = forms.CharField(required=True)
    password = forms.CharField(required=True)
    
    
views

from .forms import LoginForm
class LoginView(View):

    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        login_form = LoginForm()
        if login_form.is_valid():
            user_name = request.POST.get('username')
            pass_word = request.POST.get('password')
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                login(request, user)
                return render(request, 'index.html')
        else:
            return render(request, 'login.html', {'msg': '用户名或密码错误!'})

  • 登陆提示
class LoginView(View):

    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get('username')
            pass_word = request.POST.get('password')
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                login(request, user)
                return render(request, 'index.html')
            else:
                return render(request, 'login.html', {'msg': '用户名或密码错误!'})
        else:
            return render(request, 'login.html', {'login_form': login_form})

帐号登录

{% csrf_token %}

没有慕学在线网帐号? [立即注册]

  • 用户注册
第四章 在线教育平台(用户登录注册)_第2张图片
用户注册

用户注册通过邮箱注册界面注册,其中注册过程需要用户输入验证码,采用django-simple-captcha,于此同时,用户注册成功,需要提供用户邮箱激活,这里采用邮箱发送激活链接,保证用户操作。

{{ register_form.captcha }}
{% for key,error in register_form.errors.items %}{{ error }}{% endfor %}
{% csrf_token %}
class RegisterView(View):
    def get(self,request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form':register_form})

    def post(self,request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            username = request.POST.get('email')
            password = request.POST.get('password')
            user_register = UserProfile()
            user_register.username = username
            user_register.email = username
            user_register.password = make_password(password)
            user_register.is_active = False
            user_register.save()

            send_email(username, 'register')
            return render(request, 'login.html', {'register_form': register_form})
        else:
            return render(request, 'register.html', {'register_form': register_form})
class RegisterForm(forms.Form):
    email = forms.EmailField(required=True)
    password = forms.CharField(required=True, min_length=5)
    captcha = CaptchaField(error_messages={'invalid': '验证码不正确'})

settings


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',
    'course',
    'organization',
    'operation',
    'xadmin',
    'crispy_forms',
    'captcha'
]

# email setting
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '*****'
EMAIL_USE_TLS = False
EMAIL_FROM = '[email protected]'

urls

urlpatterns = [
    url(r'^xadmin/', xadmin.site.urls),
    url('^$', TemplateView.as_view(template_name='index.html'), name='index'),
    url('^login/$', LoginView.as_view(), name='login'),
    url('^register/$', RegisterView.as_view(), name='register'),
    url(r'^captcha/', include('captcha.urls')),
    url(r'^active/(?P.*)/$', ActiveView.as_view(), name='active')
]

email_utils

# _*_ encoding:utf-8 _*_

__author__ = 'wrj008'
__date__ = '2018/3/12 9:58'

from random import Random
from django.core.mail import send_mail

from users.models import EmailVerifyRecord
from edu_gmooc.settings import EMAIL_FROM


def random_code(randomlength=8):
    str = ''
    char = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(char) - 1
    random = Random()
    for i in range(randomlength):
        str += char[random.randint(0, length)]
    return str


def send_email(email, send_type='register'):
    email_verify = EmailVerifyRecord()
    email_verify.email = email
    code = random_code(16)
    email_verify.code = code
    email_verify.send_type = send_type
    email_verify.save()

    email_title = ''
    email_body = ''
    if send_type == 'register':
        email_title = '用户注册'
        email_body = '点击下面链接注册:http://127.0.0.1:8000/active/{0}'.format(code)
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass

  • 密码找回
第四章 在线教育平台(用户登录注册)_第3张图片
密码找回

用户进入密码找回界面,通过提交邮箱和验证码,收到修改密码地址,通过生成的随机修改密码地址,进行密码修改,修改密码需要隐藏用户账户,验证用户修改密码界面是够有输入错误,如有错误则,错误提示,没有错误则返回登录界面。


    urls
    url('^forgetpwd/$', ForgetPwdView.as_view(), name='forget_pwd'),
    
    
    froms
    
    class FogetPwdForm(forms.Form):
        email = forms.EmailField(required=True)
        captcha = CaptchaField(error_messages={'invalid': '验证码不正确'})
        
    email-send
    elif send_type == 'forget':
        email_title = '用户密码找回'
        email_body = '点击下面链接重置密码:http://127.0.0.1:8000/reset/{0}'.format(code)
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass
    
    views
    class ForgetPwdView(View):
    def get(self, request):
        forgetpwd_form = FogetPwdForm(request.POST)
        return render(request, 'forgetpwd.html',{'forgetpwd_form': forgetpwd_form})

    def post(self,request):
        forgetpwd_form = FogetPwdForm(request.POST)
        if forgetpwd_form.is_valid():
            email = request.POST.get('email')
            user = UserProfile.objects.get(email=email)
            if user is not None:
                send_email(email, 'forget')
                return render(request, 'common/mail_success.html')
            else:
                return render(request, 'forgetpwd.html', {'msg': '用户不存在', 'forgetpwd_form': forgetpwd_form})
        else:
            return render(request, 'forgetpwd.html', {'forgetpwd_form': forgetpwd_form})



    
    
    
    密码修改
    
    
    


修改密码

已经通过验证,请设置新密码

  • 新 密 码 :
  • 确定密码:
{% csrf_token %}
urls
    url(r'^reset/(?P.*)/$', ResetPwdView.as_view(), name='reset'),
    url('^modify_pwd/$', ModifyPwdView.as_view(), name='modify_pwd'),


forms
class ModifyForm(forms.Form):
    password1 = forms.CharField(required=True, min_length=5)
    password2 = forms.CharField(required=True, min_length=5)

views
class ResetPwdView(View):
    def get(self, request, active_code):
        all_actives = EmailVerifyRecord.objects.filter(code=active_code)
        if all_actives:
            for active in all_actives:
                email = active.email
            return render(request, 'password_reset.html', {'email': email})
        else:
            return render(request, 'common/active_fail.html')


class ModifyPwdView(View):
    def post(self, request):
        modifypwd_form = ModifyForm(request.POST)
        if modifypwd_form.is_valid():
            email = request.POST.get('email')
            pwd1 = request.POST.get('password1', '')
            pwd2 = request.POST.get('password2', '')
            if pwd1 == pwd2:
                user = UserProfile.objects.get(email=email)
                user.password = make_password(pwd1)
                user.save()
                return render(request, 'login.html')
            else:
                return render(request, 'password_reset.html', {'msg': '密码不一致', 'email': email})
        else:
            email = request.POST.get('email')
            return render(request, 'password_reset.html', {'email': email, 'modifypwd_form': modifypwd_form})

  • 本篇博客原视频博主[慕课在线教育平台]
  • 本篇博客撰写人: XiaoJinZi 转载请注明出处
  • 学生能力有限 附上邮箱: [email protected] 不足以及误处请大佬指责

你可能感兴趣的:(第四章 在线教育平台(用户登录注册))