Django基于form的用户登录与注册

class LoginForm(forms.Form):
    username_or_email = forms.CharField(label='用户名',
                               widget=forms.TextInput(
                                   attrs={'class': 'form-control', 'placeholder': '请输入用户名或邮箱'}))
    password = forms.CharField(label='密码',
                               widget=forms.PasswordInput(
                                   attrs={'class': 'form-control', 'placeholder': '请输入密码'}))

    def clean(self):
        username_or_email = self.cleaned_data['username_or_email']
        password = self.cleaned_data['password']
        user = auth.authenticate(username=username_or_email, password=password)

        if user is None:
            if UserProfile.objects.filter(email=username_or_email).exists():
                username = UserProfile.objects.get(email=username_or_email).username
                user = auth.authenticate(username=username, password=password)
                if not (user is None):
                    self.cleaned_data['user'] = user
                    return self.cleaned_data
                else:
                    raise forms.ValidationError('用户名或密码错误')
            else:
                raise forms.ValidationError('用户名或密码错误')
        else:
            self.cleaned_data['user'] = user
        return self.cleaned_data
LoginForm
class RegForm(forms.Form):
    username = forms.CharField(label='用户名',
                               max_length=30,
                               min_length=3,
                               widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入用户名'}))
    email = forms.EmailField(label='邮箱',
                             widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': '请输入邮箱'}))
    verification_code = forms.CharField(label='验证码',
                                        required=False,
                                        widget=forms.TextInput(
                                            attrs={'class': 'form-control', 'placeholder': '点击“发送验证码”发送到邮箱'}))
    password = forms.CharField(label='密码',
                               min_length=6,
                               widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'}))
    password_again = forms.CharField(label='再次输入密码',
                                     min_length=6,
                                     widget=forms.PasswordInput(attrs={'class': 'form-control',
                                                                       'placeholder': '请再次输入密码'}))

    def __init__(self, *args, **kwargs):
        if 'request' in kwargs:
            self.request = kwargs.pop('request')
        super(RegForm, self).__init__(*args, **kwargs)

    def clean_username(self):
        username = self.cleaned_data['username']
        if UserProfile.objects.filter(username=username).exists():
            raise forms.ValidationError('用户名已存在')
        return username

    def clean_email(self):
        email = self.cleaned_data['email']
        if UserProfile.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱已存在')
        return email

    def clean_password_again(self):
        password = self.cleaned_data['password']
        password_again = self.cleaned_data['password_again']
        if password != password_again:
            raise forms.ValidationError('两次密码输入不一致')
        return password_again

    def clean_verification_code(self):
        verification_code = self.cleaned_data['verification_code'].strip()
        if verification_code == '':
            raise forms.ValidationError('验证码不能为空')

        # 判断验证码
        code = self.request.session.get('register_code', '')
        verification_code = self.cleaned_data.get('verification_code', '')
        if not(code != '' and code == verification_code):
            raise forms.ValidationError('验证码错误')
        return verification_code
RegForm
def login(request):
    if request.method == 'POST':
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user = login_form.cleaned_data['user']
            auth.login(request, user)
            return redirect(request.GET.get('from', reverse('home')))
    else:
        login_form = LoginForm()
    context = {}
    context['login_form'] = login_form
    return render(request, 'user/login.html', context)

def register(request):
    if request.method == 'POST':
        reg_form = RegForm(request.POST, request=request)
        if reg_form.is_valid():
            username = reg_form.cleaned_data['username']
            email = reg_form.cleaned_data['email']
            password = reg_form.cleaned_data['password']
            # 创建用户
            user = UserProfile.objects.create_user(username, email, password)
            user.save()
            # 清除session
            del request.session['register_code']
            # 登录用户
            user = auth.authenticate(username=username, password=password)
            auth.login(request, user)
            return redirect(request.GET.get('from'), reverse('home'))
    else:
        reg_form = RegForm()
    context = {}
    context['reg_form'] = reg_form
    return render(request, 'user/register.html', context)
views.py
{% extends 'base.html' %}
{% block title %}我的网站|注册{% endblock %}
{% block nav_home_active %}active{% endblock %}

{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-xs-4 col-xs-offset-4">
            {% if not user.is_authenticated %}
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">注册</h3>
                    </div>
                    <div class="panel-body">
                        <form action="" method="post">
                            {% csrf_token %}
                            {% for field in reg_form %}
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field }}
                                <p class="text-danger">{{ field.errors.as_text }}</p>
                            {% endfor %}
                            <span class="pull-left text-danger">{{ reg_form.non_field_errors }}</span>
                            <div class="clearfix"></div>
                            <button id="send_code" class="btn btn-primary pull-left">发送验证码</button>
                            <input type="submit" value="注册" class="btn btn-primary pull-right">
                        </form>
                    </div>
                </div>
            </div>
            {% else %}
                <span>已登录,跳转首页。。。</span>
                <script type="text/javascript">
                    window.location.href = '/'
                </script>
            {% endif %}
        </div>
    </div>
{% endblock %}

{% block script_extends %}
    <script type="text/javascript">
        $('#send_code').click(function () {
            let email = $('#id_email').val();
            if(email===''){
                $('#tip').text('* 邮箱不能为空');
                return false;
            }
            // 发送验证码
            $.ajax({
                url: '{% url 'send_verification_code' %}',
                type: 'GET',
                data: {
                    'email': email,
                    'send_for': 'register_code',
                },
                cache: false,
                success: function (data) {
                    if(data['status']==='ERROR'){
                        alert(data['status']);
                    }
                }
            });

            // 按钮变灰
            $(this).addClass('disabled');
            $(this).attr('disabled', true);
            var time = 60;
            // 计时器
            $(this).text(time + 's');
            var interval = setInterval(() => {
                if(time<0){
                    clearInterval(interval);
                    $(this).removeClass('disabled');
                    $(this).attr('disabled', false);
                    $(this).text('发送验证码');
                    return false;
                }
                time --;
                $(this).text(time + 's');
            }, 1000);
        })
    </script>
{% endblock %}
register.html
{% extends 'base.html' %}
{% block title %}我的网站|登录{% endblock %}
{% block nav_home_active %}active{% endblock %}

{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-xs-4 col-xs-offset-4">
                {% if not user.is_authenticated %}
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h3 class="panel-title">登录</h3>
                        </div>
                        <div class="panel-body">
                            <form action="" method="post">
                                {% csrf_token %}
                                {% for field in login_form %}
                                    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                    {{ field }}
                                    <p class="text-danger">{{ field.errors.as_text }}</p>
                                {% endfor %}
                                <span class="pull-left text-danger">{{ login_form.non_field_errors }}</span>
                                <div class="clearfix"></div>
                                <a href="{% url 'forgot_password' %}" class="pull-left">忘记密码?</a>
                                <input type="submit" value="登录" class="btn btn-primary pull-right">
                            </form>
                        </div>
                    </div>
                </div>
                {% else %}
                    <span>已登录,跳转首页。。。</span>
                    <script type="text/javascript">
                        window.location.href = '/'
                    </script>
                {% endif %}
        </div>
    </div>
{% endblock %}
login.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="{% static 'css/base.css' %}">
    <link rel="stylesheet" href="{% static 'css/home.css' %}">
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
    <script type="text/javascript" src="{% static 'jquery-1.12.4.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
</head>
    {% block header_extends %}{% endblock %}
<body>
    <div class="navbar navbar-default navbar-fixed-top" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button class="navbar-toggle collapsed" data-toggle="collapse"
                        data-target="#navbar-collapse">
                     <span class="icon-bar"></span>
                     <span class="icon-bar"></span>
                     <span class="icon-bar"></span>
                 </button>
                <a class="navbar-brand" href="{% url 'home' %}">
                    个人博客网站
                </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar-collapse">
                <ul class="nav navbar-nav">
                    <li class="{% block nav_home_active %}{% endblock %}">
                        <a href="/">首页</a>
                    </li>
                    <li class="{% block nav_blog_active %}{% endblock %}">
                        <a href="{% url 'blog_list' %}">博客</a>
                    </li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                    {% if not user.is_authenticated %}
                        <li>
                            <a href="{% url 'login' %}?from={{ request.get_full_path }}">登录</a>
                        </li>
                        <li>
                            <a href="{% url 'register' %}?from={{ request.get_full_path }}">注册</a>
                        </li>
                    {% else %}
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" >
                                {% if user.has_nickname == 'error' %}
                                    {{ user.username }}
                                {% else %}
                                    {{ user.username }}({{ user.nick_name }})
                                {% endif %}
                                <span class="caret"></span>
                            </a>
                            <ul class="dropdown-menu">
                                <li><a href="{% url 'user_info' %}">个人资料</a></li>
                                <li><a href="{% url 'change_password' %}">修改密码</a></li>
                                {% if user.is_staff or user.is_superuser %}
                                    <li><a href="{% url 'xadmin:index' %}">后台管理</a></li>
                                {% endif %}
                                <li role="separator" class="divider"></li>
                                <li><a href="{% url 'logout' %}?from={{ request.get_full_path }}">退出</a></li>
                            </ul>
                        </li>
                    {% endif %}
                </ul>
            </div>
        </div>
    </div>
    {% block content %}{% endblock %}

    <!-- Modal -->
    <div class="modal fade" id="login_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <form id="login_modal_form" action="" method="post">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title">登录</h4>
                    </div>
                    <div class="modal-body">
                        {% csrf_token %}
                        {% for field in login_modal_form %}
                            <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                            {{ field }}
                            <p class="text-danger">{{ field.errors.as_text }}</p>
                        {% endfor %}
                        <span id="login_modal_tip" class="text-danger">
                            {{ login_form.non_field_errors }}
                        </span>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">登录</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $('#login_modal_form').submit(function (event) {
            event.preventDefault();
            $.ajax({
                url: '{% url 'login_for_modal' %}',
                type: 'POST',
                data: $(this).serialize(),
                cache: false,
                success: function (data) {
                    if(data['status']==='SUCCESS'){
                    window.location.reload();
                    }else{
                    $('#login_modal_tip').text('用户名或密码不正确');
                    }
                }
            });
        });
    </script>
    {% block script_extends %}{% endblock %}

</body>
</html>
base.html

 

转载于:https://www.cnblogs.com/hhtclay/p/10001747.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值