Django初步完成:登录、注册、退出

python环境:python2.7

开发工具:pycharm

项目名称:mysite5

app名称:online

settings:映射app路径

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'online',
]
View Code

 

数据库:model:

 1 # -*- coding: utf-8 -*-
 2 from __future__ import unicode_literals
 3 from django.db import models
 4 
 5 # Create your models here.python manage.py syncdb
 6 
 7 
 8 
 9 class User(models.Model):
10     username = models.CharField(max_length=50,unique=True)
11     password = models.CharField(max_length=50)
12     unique = True
13     def __unicode__(self):
14         return self.username
View Code

命令生成数据库:

python manage.py makemigrations #生成配置文件

python manage.py migrate #生成表

python manage.py createsuperuser  #生成超级用户

项目下url.py匹配:#也称一级路由

1 from django.conf.urls import url,include
2 from django.contrib import admin
3 from online import models,views
4 urlpatterns = [
5     url(r'^admin/', admin.site.urls),
6     url(r'^online/', include('online.urls')),
7 
8 ]
View Code

app下url.py:#也称二级路由

 1 from django.conf.urls import url,include
 2 from django.contrib import admin
 3 from online import models,views
 4 urlpatterns = [
 5     url(r'^admin/', admin.site.urls),
 6     url(r'^$', views.login, name='login'),
 7     url(r'^login/$', views.login, name='login'),
 8     url(r'^regist/$', views.regist, name='regist'),
 9     url(r'^index/$', views.index, name='index'),
10     url(r'^logout/$', views.logout, name='logout'),
11 ]
View Code

view.py逻辑函数:#称为视图层

 1 # -*- coding: utf-8 -*-
 2 from __future__ import unicode_literals
 3 
 4 from django.shortcuts import render
 5 
 6 # Create your views here.
 7 from django.shortcuts import render,render_to_response
 8 from django.http import HttpResponse,HttpResponseRedirect
 9 from django.template import RequestContext
10 from django import forms
11 from models import User
12 
13 #表单
14 class UserForm(forms.Form):
15     username = forms.CharField(label='用户名',max_length=100)
16     password = forms.CharField(label='密码',widget=forms.PasswordInput())
17 
18 
19 #注册
20 def regist(req):
21     if req.method == 'POST':
22         uf = UserForm(req.POST)
23         if uf.is_valid():
24             #获得表单数据
25             username = uf.cleaned_data['username']
26             password = uf.cleaned_data['password']
27             #添加到数据库
28             filterResult=User.objects.filter(username=username)
29             if len(filterResult)>0:
30                 context={'error':'用户名已存在,请从新输入!'}
31                 return  render(req,'regist.html',context)
32             else:
33                 User.objects.create(username= username,password=password)
34                 return render(req,'regust_success.html')
35     else:
36         uf = UserForm()
37     return render(req,'regist.html',{'uf':uf})
38 
39 #登陆
40 def login(req):
41     if req.method == 'POST':
42         uf = UserForm(req.POST)
43         if uf.is_valid():
44             #获取表单用户密码
45             username = uf.cleaned_data['username']
46             password = uf.cleaned_data['password']
47             #获取的表单数据与数据库进行比较
48             user = User.objects.filter(username__exact = username,password__exact = password)
49             if user:
50                 #比较成功,跳转index
51                 response = HttpResponseRedirect('/online/index/')
52                 #将username写入浏览器cookie,失效时间为3600
53                 response.set_cookie('username',username,3600)
54                 return response
55             else:
56                 #比较失败,还在login
57                 return HttpResponseRedirect('/online/login/')
58     else:
59         uf = UserForm()
60     return render(req,'login.html',{'uf':uf})
61 
62 #登陆成功
63 def index(req):
64     username = req.COOKIES.get('username','')
65     return render(req,'index.html' ,{'username':username})
66 
67 #退出
68 def logout(req):
69     response = HttpResponse('logout !!')
70     #清理cookie里保存username
71     response.delete_cookie('username')
72     return render(req,'login.html')
View Code

项目下->templates  #模板 存放HTML文件得

登录页面:index.html

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 4 <head>
 5     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 6     <title>登陆</title>
 7 </head>
 8 
 9 <body>
10 <h1>登陆页面:</h1>
11 <form method = 'post' enctype="multipart/form-data">
12     {% csrf_token %}
13      <p><label>用户名:</label><input type="text" name="username" /></p>
14     <p><label>密&nbsp&nbsp&nbsp&nbsp码:</label><input type="password" name="password"/></p>
15 {#    {{uf.as_p}}#}
16     <input type="submit" value = "ok" />
17 </form>
18 <br>
19 <a href="http://127.0.0.1:8000/online/regist/">注册</a>
20 </body>
21 </html>
View Code

注册页面:regist.html

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 4 <head>
 5     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 6     <title>注册</title>
 7 </head>
 8 
 9 <body>
10 <h1>注册页面:</h1>
11 <form method = 'post' enctype="multipart/form-data">
12     {% csrf_token %}
13     {{ error }}
14     <p><label>用户名:</label><input type="text" name="username" /></p>
15     <p><label>密&nbsp&nbsp&nbsp&nbsp码:</label><input type="password" name="password"/></p>
16     <input type="submit" value = "ok" />
17 </form>
18 <br>
19 <a href="http://127.0.0.1:8000/online/login/">登陆</a>
20 </body>
21 </html>
View Code

注册成功页面:login.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <p>注册成功!</p>
 9 <a href="http://127.0.0.1:8000/online/login/">登陆</a>
10 </body>
11 </html>
View Code

 

登录成功页面:index.html

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 4 <head>
 5     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 6     <title></title>
 7 </head>
 8 
 9 <body>
10 <h1>welcome {{username}} !</h1>
11 <br>
12 <a href="http://127.0.0.1:8000/online/logout/">退出</a>
13 </body>
14 </html>
View Code

 

最后把服务器端口改成自己电脑得IP地址:

我是在pycharm里面改的

最后让所有人都可以访问:

在settings.py最下面添加

ALLOWED_HOSTS = ['*']

 

 

 

 

 

 

posted @ 2018-03-22 11:37  努力乄小白  阅读(2109)  评论(0编辑  收藏  举报