【django之form和认证系统小练习】

作业要求:

作业 :
基于form表单和form组件作业注册页面

基于认证系统实现登录,注册,注销,修改密码

 

"""
Django settings for day20_test project.

Generated by 'django-admin startproject' using Django 1.11.4.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^m)b0s8r#f!!74ebp*)chk3d%cbjp1%_vhtck!(x4-u!i+oxzj'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'test01.apps.Test01Config',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'day20_test.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'day20_test.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
settings.py

 

"""day20_test URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/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 test01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^reg_form/',views.reg_form),
    url(r'^login/',views.login),
    url(r'^index/',views.index),
    url(r'^logout/',views.logout),
    # url(r'^edit_info/',views.edit_info),
]
urls.py

 

from django.shortcuts import render,redirect

# Create your views here.
from django.contrib import auth


def login(request):
    if request.method=="POST":
        user=request.POST.get("user")
        pwd=request.POST.get("pwd")
        print("user:",request.user)
        user=auth.authenticate(username=user,password=pwd)
        if user:
            # obj=redirect("/index/")
            # obj.set_cookie("is_login",True,max_age=5)
            # obj.set_cookie("user",user)
            # return obj

            auth.login(request,user)
            print("user2:", request.user)
            # request.session["user"]=user

            return redirect("/index/")

    return render(request, "login.html")

def index(request):

    user=request.user

    username=user.username
    # user=request.session.get("user")

    if not user:
        return redirect("/login/")

    # if not request.COOKIES.get("is_login"):
    #     return redirect("/login/")
    # user=request.COOKIES.get("user")
    # user=request.user
    #
    # username=user.username
    return render(request,"index.html",locals())

def logout(request):
    auth.logout(request)
    return redirect("/login/")



from django.contrib.auth.models import User
from django import forms
from django.forms import widgets
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError

class RegForm(forms.Form):
    user=forms.CharField(label="用户名",min_length=3,max_length=8,
                         widget=widgets.TextInput(attrs={"class": "form-control"}),
                         error_messages={"min_length":"输入不得少于三位","required":"不能为空","max_length":"输入不得超过8位"})

    pwd=forms.CharField(label="密码",min_length=5,
                        widget=widgets.PasswordInput(attrs={"class":"form-control"}),
                        error_messages={"min_length":"输入不得少于三位", "required": "不能为空"}
                        )

    def clean_user(self):
        val=self.cleaned_data.get("user")

        if not val.isdigit():
            return val
        else:
            raise ValidationError("用户名不能是纯数字!")

    def clean_pwd(self):
        val=self.cleaned_data.get("pwd")

        if not val.isdigit():
            return val
        else:
            raise ValidationError("密码不能是纯数字!")

def reg_form(request):
    if request.method=="POST":
        reg_form=RegForm(request.POST)
        if reg_form.is_valid():
            user=request.POST.get("user")
            pwd=request.POST.get("pwd")
            user=User.objects.create_user(username=user,password=pwd)
            print(reg_form.cleaned_data)
            return redirect("/login/")
        else:
            return render(request, "reg_form.html", locals())

    reg_form=RegForm()
    return render(request, "reg_form.html", locals())
views.py

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

</head>
<body>

<h3 style="color: blue">欢迎回来</h3>

{% if  user.is_authenticated %}
  <h3>你好 {{ username }} 新春快乐</h3>
    <hr>
  <p><a href="/logout/">注销</a></p>
 {% else %}
    <a href="/login/">登录</a>
    <a href="">注册</a>
{% endif %}

<img class="img1" src="1.jpg" alt="">

</body>
</html>
index.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>

<div style="width: 500px;margin: 0 auto;margin-top: 80px;">
    <h2>登录界面</h2>
    <p></p>
    <hr>
    <form class="form-horizontal" action="" method="post">
        {% csrf_token %}
        <div class="form-group">
            <label for="n1" class="col-sm-2 control-label">用户名</label>
            <div class="col-sm-10">
                <input id="n1" type="text" name="user" class="form-control" placeholder="用户名">
            </div>
        </div>
        <p></p>
        <p></p>
        <div class="form-group">
            <label for="n2" class="col-sm-2 control-label">密码</label>
            <div class="col-sm-10">
                <input id="n2" type="password" name="pwd" class="form-control" placeholder="密码">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit"  class="btn btn-primary">
            </div>
        </div>
    </form>
</div>


</body>
</html>
login.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>

<hr>

<div class="container">
    <h2>注册界面</h2>
    <hr>
    <div class="row">
        <div class="col-md-5">
            <form action="" method="post" novalidate>
                {% csrf_token %}
                <div class="form-group">
{#                    <label for="">{{ reg_form.user.label }}</label>#}
                    <label for="">请输入用户名</label>
                    {{ reg_form.user }} <span>{{ reg_form.errors.user.0 }}</span>
                </div>
                <div class="form-group">
{#                    <label for="">{{ reg_form.pwd.label }}</label>#}
                    <label for="">请输入密码</label>
                    {{ reg_form.pwd }} <span>{{ reg_form.errors.pwd.0 }}</span>
                </div>
                <input type="submit" class="btn btn-primary">
            </form>
        </div>
    </div>
</div>


</body>
</html>
reg_form.html

 

posted @ 2018-03-07 15:09  小火星_Hirsi  阅读(223)  评论(0编辑  收藏  举报