Django小白教程之Django用户注册与登录


Posted in Python onApril 22, 2016

 Django 是由 Python 开发的一个免费的开源网站框架,可以用于快速搭建高性能,优雅的网站!

学习django学得超级吃力,最近弄个最简单的用户登录与注册界面都是那么难,目前算是基本实现了,虽然功能特别特别简单但是做一个记录,以后学习深入了再来补充:

首先创建项目,到项目所在目录:django-admin startproject demo0414_userauth

进入项目:cd demo0414_userauth

创建相应的app:django-admin startapp account

整个项目的结构图如图所示

├── account
│ ├── admin.py
│ ├── admin.pyc
│ ├── apps.py
│ ├── init.py
│ ├── init.pyc
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0001_initial.pyc
│ │ ├── init.py
│ │ └── init.pyc
│ ├── models.py
│ ├── models.pyc
│ ├── tests.py
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
├── demo0414_userauth
│ ├── init.py
│ ├── init.pyc
│ ├── settings.py
│ ├── settings.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── wsgi.py
│ └── wsgi.pyc
├── manage.py
└── templates
├── register.html
├── success.html
└── userlogin.html

4 directories, 29 files

然后在setting文件的installed_app中添加app account;

Django小白教程之Django用户注册与登录 

创建一个templates文件夹,可以放在项目的根目录下也可以放在app的目录下。一般情况下提倡放在app的目录下。如果放下项目的根目录下需要在setting文件中TEMPLATES中设置'DIRS': [os.path.join(BASE_DIR,'templates')],否则不能使用模板。

Django小白教程之Django用户注册与登录 

另外因为这个项目存在页面跳转的问题,为了安全防止csrf攻击,一把模板中都有了相关的设置。目前我还不会用这个东西,据说在form表单中添加标签{% csrf_token %}就可以实现了,但是我没有成功。所以先不考虑这个问题,把seeting中的这个中间件'django.middleware.csrf.CsrfViewMiddleware',注释掉

Django小白教程之Django用户注册与登录 

然后在model中创建相应的数据库:

class User(models.Model):
 username = models.CharField(max_length=50)
 password = models.CharField(max_length=50)
 email = models.EmailField()

view中添加相应的程序。Pdb当时用于断点调试,我很喜欢,超级喜欢。如果你不敢兴趣,直接注释即可。

#coding=utf-8
from django.shortcuts import render,render_to_response
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from django.contrib import auth
from models import User

import pdb

def login(request): 
 if request.method == "POST":
  uf = UserFormLogin(request.POST)
  if uf.is_valid():
   #获取表单信息
   username = uf.cleaned_data['username']
   password = uf.cleaned_data['password']   
   userResult = User.objects.filter(username=username,password=password)
   #pdb.set_trace()
   if (len(userResult)>0):
    return render_to_response('success.html',{'operation':"登录"})
   else:
    return HttpResponse("该用户不存在")
 else:
  uf = UserFormLogin()
return render_to_response("userlogin.html",{'uf':uf})
def register(request):
 curtime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime());
 if request.method == "POST":
  uf = UserForm(request.POST)
  if uf.is_valid():
   #获取表单信息
   username = uf.cleaned_data['username']
   #pdb.set_trace()
   #try:
   filterResult = User.objects.filter(username = username)
   if len(filterResult)>0:
    return render_to_response('register.html',{"errors":"用户名已存在"})
   else:
    password1 = uf.cleaned_data['password1']
    password2 = uf.cleaned_data['password2']
    errors = []
    if (password2 != password1):
     errors.append("两次输入的密码不一致!")
     return render_to_response('register.html',{'errors':errors})
     #return HttpResponse('两次输入的密码不一致!,请重新输入密码')
    password = password2
    email = uf.cleaned_data['email']
   #将表单写入数据库
    user = User.objects.create(username=username,password=password1)
    #user = User(username=username,password=password,email=email)
    user.save()
    pdb.set_trace()
   #返回注册成功页面
    return render_to_response('success.html',{'username':username,'operation':"注册"})
 else:
  uf = UserForm()
return render_to_response('register.html',{'uf':uf})
class UserForm(forms.Form):
 username = forms.CharField(label='用户名',max_length=100)
 password1 = forms.CharField(label='密码',widget=forms.PasswordInput())
 password2 = forms.CharField(label='确认密码',widget=forms.PasswordInput())
 email = forms.EmailField(label='电子邮件')
class UserFormLogin(forms.Form):
 username = forms.CharField(label='用户名',max_length=100)
 password = forms.CharField(label='密码',widget=forms.PasswordInput())

Tempaltes文件夹下总共有3个页面:

Register.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>用户注册</title>
</head>
 <style type="text/css">
 body{color:#efd;background:#453;padding:0 5em;margin:0}
 h1{padding:2em 1em;background:#675}
 h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
 p{margin:1em 0}
 </style>
<body>
<h1>注册页面:</h1>
<form method = 'post' enctype="multipart/form-data">
{{uf.as_p}}
{{errors}}
</br>
<input type="submit" value = "ok" />
</form>
</body>
</html>

Userlogin.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>用户注册</title>
</head>
 <style type="text/css">
 body{color:#efd;background:#453;padding:0 5em;margin:0}
 h1{padding:2em 1em;background:#675}
 h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
 p{margin:1em 0}
 </style>
<body>
<h1>登录页面:</h1>
<form method = 'post' enctype="multipart/form-data">
{{uf.as_p}}
<input type="submit" value = "ok" />
</form>
</body>
</html>

Success.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title></title>
</head>
<body>
<form method = 'post'>
 <h1>恭喜,{{operation}}成功!</h1>
</form>
</body>
</html>

更新数据库:

Django小白教程之Django用户注册与登录 

运行服务器:

Django小白教程之Django用户注册与登录 

注册页面:

Django小白教程之Django用户注册与登录 

如果注册的用户没有注册过,则能注册成功点击OK进入success界面

登录页面:

Django小白教程之Django用户注册与登录 

点击OK就能进入到success页面

关于Django用户注册与登录教程就给大家介绍完了,希望对大家有所帮助!

Python 相关文章推荐
Python实现屏幕截图的代码及函数详解
Oct 01 Python
在CentOS6上安装Python2.7的解决方法
Jan 09 Python
Python实现的简单排列组合算法示例
Jul 04 Python
python爬取哈尔滨天气信息
Jul 14 Python
解决python写入带有中文的字符到文件错误的问题
Jan 31 Python
详解利用Python scipy.signal.filtfilt() 实现信号滤波
Jun 05 Python
Python 实现还原已撤回的微信消息
Jun 18 Python
Python 进程之间共享数据(全局变量)的方法
Jul 16 Python
解决Python使用列表副本的问题
Dec 19 Python
python标识符命名规范原理解析
Jan 10 Python
2020新版本pycharm+anaconda+opencv+pyqt环境配置学习笔记,亲测可用
Mar 24 Python
在主流系统之上安装Pygame的方法
May 20 Python
python中PIL安装简单教程
Apr 21 #Python
Python for Informatics 第11章之正则表达式(四)
Apr 21 #Python
Python for Informatics 第11章之正则表达式(二)
Apr 21 #Python
Python for Informatics 第11章 正则表达式(一)
Apr 21 #Python
编写Python爬虫抓取暴走漫画上gif图片的实例分享
Apr 20 #Python
Ruby使用eventmachine为HTTP服务器添加文件下载功能
Apr 20 #Python
Python实现HTTP协议下的文件下载方法总结
Apr 20 #Python
You might like
PHP实现递归无限级分类
2015/10/22 PHP
PHP实现原生态图片上传封装类方法
2016/11/08 PHP
php 多进程编程父进程的阻塞与非阻塞实例分析
2020/02/22 PHP
如何制作浮动广告 JavaScript制作浮动广告代码
2012/12/30 Javascript
js每隔5分钟执行一次ajax请求的实现方法
2013/11/27 Javascript
jQuery 选择器详解
2015/01/19 Javascript
详解JS面向对象编程
2016/01/24 Javascript
原生JavaScript实现AJAX、JSONP
2017/02/07 Javascript
JavaScript实现的商品抢购倒计时功能示例
2017/04/17 Javascript
在使用JSON格式处理数据时应该注意的问题小结
2017/05/20 Javascript
Vue+tracking.js 实现前端人脸检测功能
2020/04/16 Javascript
[08:47]DOTA2每周TOP10 精彩击杀集锦vol.6
2014/06/25 DOTA
Python中的defaultdict模块和namedtuple模块的简单入门指南
2015/04/01 Python
利用Python爬虫给孩子起个好名字
2017/02/14 Python
对python 操作solr索引数据的实例详解
2018/12/07 Python
Python3利用print输出带颜色的彩色字体示例代码
2019/04/08 Python
Django如何开发简单的查询接口详解
2019/05/17 Python
python 应用之Pycharm 新建模板默认添加编码格式-作者-时间等信息【推荐】
2019/06/17 Python
Python实现二叉搜索树BST的方法示例
2019/07/30 Python
Python Django 封装分页成通用的模块详解
2019/08/21 Python
python-tornado的接口用swagger进行包装的实例
2019/08/29 Python
用python解压分析jar包实例
2020/01/16 Python
无惧面试,带你搞懂python 装饰器
2020/08/17 Python
Armor Lux法国官方网站:水手服装、成衣和内衣
2020/05/26 全球购物
华三通信H3C面试题
2015/05/15 面试题
计算机专业毕业生自荐信
2013/12/31 职场文书
修理厂厂长岗位职责
2014/01/30 职场文书
自行车广告词大全
2014/03/21 职场文书
科技工作者先进事迹
2014/08/16 职场文书
责任书范本
2014/08/25 职场文书
2015年党员个人工作总结
2015/05/13 职场文书
《风筝》教学反思
2016/02/23 职场文书
2016基督教会圣诞节开幕词
2016/03/04 职场文书
创业计划书之寿司
2019/07/19 职场文书
《鲁班学艺》读后感3篇
2019/11/27 职场文书
python实现一个简单的贪吃蛇游戏附代码
2022/06/28 Python