搭建自己的博客(二十一):通过django表单实现登录注册

1、变化的部分

2、上代码:

{# 引用模板 #}
{% extends 'base.html' %}

{% load staticfiles %}
{% block header_extends %}
    <link rel="stylesheet" href="{% static 'blog/blog.css' %}">
{% endblock %}


{# 标题 #}
{% block title %}
    {{ blog.title }}
{% endblock %}

{# 内容#}
{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-10 offset-1">
                <ul class="blog-info-description">
                    <h3>{{ blog.title }}</h3>
                    <li>作者:{{ blog.author }}</li>
                    {# 时间过滤器让时间按照自己需要的格式过滤 #}
                    <li>发布日期:{{ blog.created_time|date:"Y-m-d H:n:s" }}</li>
                    <li>分类:
                        <a href="{% url 'blogs_with_type' blog.blog_type.pk %}">
                            {{ blog.blog_type }}
                        </a>
                    </li>
                    <li>阅读({{ blog.get_read_num }})</li>
                </ul>
                <p class="blog-content">{{ blog.content|safe }}</p>


                <p>上一篇:
                    {% if previous_blog %}
                        <a href="{% url 'blog_detail' previous_blog.pk %}">{{ previous_blog.title }}</a>
                    {% else %}
                        <span>没有了</span>
                    {% endif %}
                </p>
                <p>下一篇:
                    {% if next_blog %}
                        <a href="{% url 'blog_detail' next_blog.pk %}">{{ next_blog.title }}</a>
                    {% else %}
                        <span>没有了</span>
                    {% endif %}
                </p>
            </div>
        </div>
        <div class="row">
            <div class="col-10 offset-1">
                <div class="comment-area">
                    <h3 class="comment-area-title">提交评论</h3>
                    {% if user.is_authenticated %}
                        <form action="{% url 'update_comment' %}" method="post" style="overflow: hidden">
                            {% csrf_token %}
                            <div class="form-group">
                                <label for="form-control">{{ user.username }},欢迎评论~</label>
                                <textarea class="form-control" name="text" id="comment_text" rows="4"></textarea>
                            </div>
                            <input type="hidden" name="object_id" value="{{ blog.pk }}">
                            <input type="hidden" name="content_type" value="blog">
                            <input type="submit" value="评论" class="btn btn-primary float-right">
                        </form>
                    {% else %}
                        您尚未登录,登录之后方可评论
                        {# 提交登录的时候带上从哪里访问的路径 #}
                        <a class="btn btn-primary" href="{% url 'login' %}?from={{ request.get_full_path }}">登录</a>
                        <span> or </span>
                        <a class="btn-danger btn" href="{% url 'register' %}?from={{ request.get_full_path }}">注册</a>
                    {% endif %}
                </div>
                <div class="-comment-area">
                    <h3 class="comment-area-title">评论列表</h3>
                    {% for comment in comments %}
                        <div>
                            {{ comment.user.username }}
                            {{ comment.comment_time|date:"Y-m-d H:n:s" }}
                            {{ comment.text }}
                        </div>
                    {% empty %}

                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script>
        $(".nav-blog").addClass("active").siblings().removeClass("active");
    </script>
{% endblock %}
blog_detail.html
# -*- coding: utf-8 -*-
# @Time    : 18-11-20 下午8:10
# @Author  : Felix Wang

from django import forms
from django.contrib import auth
from django.contrib.auth.models import User


class LoginForm(forms.Form):
    username = forms.CharField(label='用户名', required=True,
                               widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入用户名'}))
    # widget指定input标签类型
    password = forms.CharField(label='密码',
                               widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'}))

    def clean(self):  # 验证数据
        username = self.cleaned_data['username']
        password = self.cleaned_data['password']
        user = auth.authenticate(username=username, password=password)
        if user is None:
            raise forms.ValidationError('用户名或密码错误')
        self.cleaned_data.user = user  # 将验证过的user放入clean_data
        return self.cleaned_data


class RegisterForm(forms.Form):
    # 用户名字段
    username = forms.CharField(label='用户名',
                               max_length=30,
                               min_length=3,
                               required=True,
                               widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入用户名'}))
    # 邮箱字段
    email = forms.EmailField(label='邮箱',
                             min_length=3,
                             required=True,
                             widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': '请输入邮箱'}))
    # 密码字段
    password = forms.CharField(label='密码',
                               min_length=6,
                               required=True,
                               widget=forms.PasswordInput(
                                   attrs={'class': 'form-control', 'placeholder': '请输入密码'}))
    # 再次输入密码
    password_again = forms.CharField(label='确认密码',
                                     min_length=6,
                                     required=True,
                                     widget=forms.PasswordInput(
                                         attrs={'class': 'form-control', 'placeholder': '请再输入一次密码'}))

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

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.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
forms.py
"""myblog URL Configuration

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

urlpatterns = [
    path('', views.home, name='home'),  # 主页路径
    path('admin/', admin.site.urls),
    path('ckeditor', include('ckeditor_uploader.urls')),  # 配置上传url
    path('blog/', include('blog.urls')),  # 博客app路径
    path('comment/', include('comment.urls')),  # 博客app路径
    path('login/', views.login, name='login'),  # 登录
    path('register/', views.register, name='register'),  # 登录
]

# 设置ckeditor的上传
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urls.py
# -*- coding: utf-8 -*-
# @Time    : 18-11-7 下午4:12
# @Author  : Felix Wang

from django.shortcuts import render, redirect
from django.contrib.contenttypes.models import ContentType
from django.contrib import auth
from django.contrib.auth.models import User
from django.urls import reverse
from read_statistics.utils import get_seven_days_read_data, get_x_days_hot_data
from blog.models import Blog
from .forms import LoginForm, RegisterForm


def home(requests):
    blog_content_type = ContentType.objects.get_for_model(Blog)
    dates, read_nums = get_seven_days_read_data(blog_content_type)

    context = {
        'read_nums': read_nums,
        'dates': dates,
        'today_hot_data': get_x_days_hot_data(0),  # 获取今日热门
        'yesterday_hot_data': get_x_days_hot_data(1),  # 获取昨日热门
        'seven_days_hot_data': get_x_days_hot_data(7),  # 获取周热门
        'one_month_hot_data': get_x_days_hot_data(30),  # 获取月热门
    }
    return render(requests, 'home.html', context)


def login(requests):
    # 如果是form表单提交验证登录
    if requests.method == 'POST':
        login_form = LoginForm(requests.POST)
        if login_form.is_valid():  # 验证是否通过
            # 因为在form表单验证过了,所以不用自己再验证
            user = login_form.cleaned_data.get('user')
            auth.login(requests, user)
            return redirect(requests.GET.get('from', reverse('home')))
        else:
            login_form.add_error(None, '用户名或密码不正确')
    else:
        login_form = LoginForm()
    context = {
        'login_form': login_form,
    }
    return render(requests, 'login.html', context)


def register(requests):
    if requests.method == 'POST':
        reg_form = RegisterForm(requests.POST)
        if reg_form.is_valid():
            username = reg_form.cleaned_data['username']
            email = reg_form.cleaned_data['email']
            password = reg_form.cleaned_data['password']

            # 创建用户
            user = User.objects.create_user(username=username, email=email, password=password)
            user.save()

            # 登录用户
            user = auth.authenticate(username=username, password=password)
            auth.login(requests, user)
            # 登录之后跳转
            return redirect(requests.GET.get('from', reverse('home')))
    else:
        reg_form = RegisterForm()

    context = {
        'reg_form': reg_form,
    }
    return render(requests, 'register.html', context)
mylog下的views.py
{% extends 'base.html' %}
{% load staticfiles %}


{% block title %}
    我的博客|登录
{% endblock %}

{% block content %}
    <div class="container">
        <div class="col-xl-6 offset-xl-3">
            <div class="card">
                <h5 class="card-header">登录</h5>
                <div class="card-body">
                    <form action="{% url 'login' %}" 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="text-danger float-left">{{ login_form.non_field_errors }}</span>
                        <input type="submit" value="登录" class="btn btn-primary float-right">
                    </form>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    {# 将首页这个按钮设置激活状态 #}
    <script>
        $(".nav-home").addClass("active").siblings().removeClass("active");
    </script>
{% endblock %}
login.html
{% extends 'base.html' %}
{% load staticfiles %}


{% block title %}
    我的博客|登录
{% endblock %}

{% block content %}
    <div class="container">
        <div class="col-xl-6 offset-xl-3">
            <div class="card">
                <h5 class="card-header">登录</h5>
                <div class="card-body">
                    <form action="{% url 'login' %}" 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="text-danger float-left">{{ login_form.non_field_errors }}</span>
                        <input type="submit" value="登录" class="btn btn-primary float-right">
                    </form>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    {# 将首页这个按钮设置激活状态 #}
    <script>
        $(".nav-home").addClass("active").siblings().removeClass("active");
    </script>
{% endblock %}
register.html

猜你喜欢

转载自www.cnblogs.com/felixwang2/p/9992178.html