Python入门 实例Django实现登录 注册

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

0x00 入门前言

对于初学者而言,“入门”一门语言最重要的不是记住变量、字典、列表、对象等的所有用法就能被称之为入门,所谓“入门”就是当遇到一个实际应用场景时,第一时间能想到使用代码实现,即为入门。当然有人会说,不记住基础的东西怎么能会写出想要的代码呢?找茬的请绕路!!!入门一门语言肯定是需要学习变量、字典、列表、对象等等基础语法,但最重要的是:有一个可用功能实例让其练手,感受一下所学基础语法在应用场景中的配合用法,也可以大大提高初学者的积极性和自信心,此文将使用Django实现登录、注册

0x01 前言引导

至于Django怎么“新建项目工程”,和在工程中“新建应用”,以及django中各文件的用途此文不做讨论,有需要的可以查看该博客中的其它文章。
前文登录、注册、退出(http://blog.csdn.net/foryouslgme/article/details/51377385)可做参考,如果有疑问,可以相互讨论

0x02 正式开始

项目目录结构

login/
├── db.sqlite3
├── logReg  #新建的应用文件夹
│   ├── __init__.py
│   ├── admin.py
│   ├── migrations  
│   │   ├── 0001_initial.py
│   │   └── __init__.py
│   ├── models.py   #数据模型脚本
│   ├── templates   #模板目录,需要自己手工创建
│   │   ├── index.html
│   │   ├── login.html
│   │   └── regist.html
│   ├── tests.py
│   └── views.py        #视图处理脚本,所有处理过程都由此设置
├── login       #与项目名一样的文件夹是整个项目的配置文件夹,django版本不一样,目录结构也不一样
│   ├── __init__.py
│   ├── settings.py #全局设置脚本,常用的是添加应用
│   ├── urls.py
│   └── wsgi.py
└── manage.py   #项目管理脚本,可以创建应用和启动项目等

应用开发

#setting.py
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'logReg',    #添加新建的应用
)
#urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'login.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)), #系统默认存在,是后台管理员使用url,以下均由个人创建,至于用法,可以参考[urls.py配置](http://blog.csdn.net/foryouslgme/article/details/51362824)
    url(r'^login/$', 'logReg.views.login',name='login'),
    url(r'^regist/$', 'logReg.views.regist',name='regist'),
    url(r'^index/$', 'logReg.views.index',name='index'),
    url(r'^logout/$', 'logReg.views.logout',name='logout'),
)
#models.py
from django.db import models

# Create your models here.
class User(models.Model):
    username = models.CharField(max_length=30)
    password = models.CharField(max_length=30)

    def __unicode__(self):
        return self.username
#coding:utf-8
#views.py
from django.shortcuts import render
from django import forms
from models import User
from django.http import HttpResponseRedirect,HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response

# Create your views here.
class UserForm(forms.Form):
    username = forms.CharField(label='用户名',max_length=100)
    password = forms.CharField(label='密__码',widget=forms.PasswordInput())

def regist(req):
    Method = req.method
    if Method == 'POST':
        #如果有post提交的动作,就将post中的数据赋值给uf,供该函数使用
        uf = UserForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']

            try:
                registJudge = User.objects.filter(username=username).get().username
                return render_to_response('regist.html',{'registJudge':registJudge})
            except :
                registAdd = User.objects.create(username=username,password=password)
            #registAdd = User.objects.get_or_create(username=username,password=password)[1]
            #if registAdd == False:
                return render_to_response('regist.html',{'registAdd':registAdd,'username':username})



    else:
        uf = UserForm()
    return render_to_response('regist.html',{'uf':uf,'Method':Method},context_instance=RequestContext(req))


def login(req):
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            #对比输入的用户名和密码和数据库中是否一致
            userPassJudge = User.objects.filter(username__exact=username,password__exact=password)

            if userPassJudge:
                response = HttpResponseRedirect('/index/')
                response.set_cookie('cookie_username',username,3600)
                return response
            else:
                return HttpResponse('login.html')
    else:
        uf = UserForm()
    return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))



def index(req):
    username = req.COOKIES.get('cookie_username','')
    return render_to_response('index.html',{'username':username})

def logout(req):
    response = HttpResponse('logout!<br><a href="127.0.0.1:8000/regist>regist</a>"')
    response.delete_cookie('cookie_username')
    return  response
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
<form method="post">
    {% csrf_token %}
    {{uf.as_p}}
    <input type="submit" value="login">
    <br>
    <a href="http://127.0.0.1:8000/regist">regist</a>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>Regist</title>
</head>
<body>

{% if Method == 'GET' %}
    <form method ="post">
        {% csrf_token %}
        {{uf.as_p}}
        <input type="submit" name="regist" value="regist">
    </form>
{% else %}
    {% if username %}
        {{username}} regist is success!
        <br>
        <a href="http://127.0.0.1:8000/login">login</a>
    {% else %}
        {{ registJudge }}  is exist!
        <br>
        <a href="http://127.0.0.1:8000/regist">regist</a>
    {% endif %}
{% endif %}
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
<h1>Welcome {{ username }}!</h1>

<br>
<a href="http://127.0.0.1:8000/logout">退出</a>
<br>
<a href="http://127.0.0.1:8000/login">登录</a>
<br>
<a href="http://127.0.0.1:8000/regist">注册</a>
</body>
</html>

实现效果

  • 首页
  • 注册页
  • 注册成功
  • 注册失败
  • 登录页面
  • 登录成功
  • 退出

点这里可以跳转到人工智能网站

发表评论