首页 > 代码库 > python day19
python day19
form 验证时,会根据设置报错
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^login/‘, views.login),
]
views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
from django import forms
class LoginForm(forms.Form):
user = forms.CharField(required=True)
pwd = forms.CharField(required=True)
import json
def login(request):
if request.method == ‘POST‘:
result = {‘status‘: False, ‘message‘: None}
obj = LoginForm(request.POST)
ret = obj.is_valid()
if ret:
print(obj.clean())
result[‘status‘] = True
else:
from django.forms.utils import ErrorDict
#print(type(obj.errors),obj.errors.as_json())
error_str = obj.errors.as_json()
result[‘message‘] = json.loads(error_str)
return HttpResponse(json.dumps(result))
return render(request, ‘login.html‘)
settings.py
MIDDLEWARE_CLASSES = [
‘django.middleware.security.SecurityMiddleware‘,
‘django.contrib.sessions.middleware.SessionMiddleware‘,
‘django.middleware.common.CommonMiddleware‘,
#‘django.middleware.csrf.CsrfViewMiddleware‘,
‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
‘django.contrib.auth.middleware.SessionAuthenticationMiddleware‘,
‘django.contrib.messages.middleware.MessageMiddleware‘,
‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
]
STATIC_URL = ‘/static/‘
STATICFILES_DIRS = (
os.path.join(BASE_DIR,‘static‘),
)
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.error-msg{
color: red;
}
</style>
</head>
<body>
<div>
<div>
<input type="text" name="user" />
</div>
<div>
<input type="password" name="pwd" />
</div>
<input type="button" value=http://www.mamicode.com/"提交" onclick="DoSubmit();" />
</div>
<script src=http://www.mamicode.com/"/static/jquery-2.1.4.min.js"></script>
<script>
function DoSubmit(){
var input_dict = {};
$(‘input‘).each(function(){
var v = $(this).val();
var n = $(this).attr(‘name‘);
input_dict[n] = v;
});
console.log(input_dict);
$(‘.error-msg‘).remove();
$.ajax({
url: ‘/login/‘,
type: ‘POST‘,
data: input_dict,
dataType: ‘json‘,
success: function (result) {
if(result.status){
location.href = http://www.mamicode.com/‘/index/‘;
}else{
$.each(result.message, function (k,v) {
console.log(k,v[0].message);
// <span class="error-msg">错误信息</span>
var tag = document.createElement(‘span‘);
tag.className = ‘error-msg‘;
tag.innerText = v[0].message;
// input[name="user"]
$(‘input[name="‘ + k + ‘"]‘).after(tag);
})
}
},
error: function () {
}
})
}
</script>
</body>
</html>
访问
http://127.0.0.1:8000/login/
CSRF 从COOKIE中调取存入
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^login/‘, views.login),
url(r‘^csrf/‘, views.csrf),
]
settings.py
MIDDLEWARE_CLASSES = [
‘django.middleware.security.SecurityMiddleware‘,
‘django.contrib.sessions.middleware.SessionMiddleware‘,
‘django.middleware.common.CommonMiddleware‘,
‘django.middleware.csrf.CsrfViewMiddleware‘,
‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
‘django.contrib.auth.middleware.SessionAuthenticationMiddleware‘,
‘django.contrib.messages.middleware.MessageMiddleware‘,
‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
]
static
jquery.cookie.js
views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
from django import forms
from django.core.exceptions import ValidationError
import re
def mobile_validate(value):
mobile_re = re.compile(r‘^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$‘)
if not mobile_re.match(value):
raise ValidationError(‘手机号码格式错误‘)
class LoginForm(forms.Form):
user = forms.CharField(required=True, error_messages={‘required‘: ‘用户名不能为空.‘})
pwd = forms.CharField(required=True,
min_length=6,
max_length=10,
error_messages={‘required‘: ‘密码不能为空.‘, ‘min_length‘: "至少6位"})
num = forms.IntegerField(error_messages={‘required‘: ‘数字不能空.‘,‘invalid‘: ‘必须输入数字‘})
phone = forms.CharField(validators=[mobile_validate, ],)
#test = forms.CharField(widget=forms.Textarea(attrs={‘class‘: ‘c1‘}))
test_choices = (
(0, ‘上海‘),
(1, ‘背景‘),
)
test = forms.IntegerField(widget=forms.Select(choices=test_choices))
def login(request):
if request.POST:
objPost = LoginForm(request.POST)
ret = objPost.is_valid()
if ret:
print(objPost.clean())
else:
from django.forms.utils import ErrorDict
#print(type(obj.errors),obj.errors.as_json())
# obj1.errors
pass
return render(request, ‘login.html‘,{‘obj1‘: objPost})
else:
objGet = LoginForm()
return render(request, ‘login.html‘,{‘obj1‘: objGet})
def csrf(request):
return render(request,‘csrf.html‘)
csrf.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/csrf/" method="post">
{% csrf_token %}
<input type="text" name="v" />
<input type="submit" value=http://www.mamicode.com/"提交" />
</form>
<input type="button" value=http://www.mamicode.com/"Ajax提交" onclick="DoAjax();" />
<script src=http://www.mamicode.com/"/static/jquery-2.1.4.min.js"></script>
<script src=http://www.mamicode.com/"/static/jquery.cookie.js"></script>
<script>
// 去cookie中获取值
var csrftoken = $.cookie(‘csrftoken‘);
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
function DoAjax(){
$.ajax({
url: ‘/csrf/‘,
type: ‘POST‘,
data: {‘k1‘: ‘v1‘},
success: function (data) {
console.log(data);
}
})
}
</script>
</body>
</html>
访问
http://127.0.0.1:8000/csrf/
session 验证登录
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^login/‘, views.login),
url(r‘^csrf/‘, views.csrf),
url(r‘^session_index/‘, views.session_index),
url(r‘^session_login/‘, views.session_login),
url(r‘^session_logout/‘, views.session_logout),
]
views.py
USER_LIST = [‘alex‘,‘eric‘,‘wangminglong‘,‘hu‘]
def session_login(request):
if request.method == ‘POST‘:
u = request.POST.get(‘user‘)
p = request.POST.get(‘pwd‘)
if p == ‘123‘ and u in USER_LIST:
request.session[‘user‘] = u
return redirect(‘/session_index/‘)
return render(request,‘session_login.html‘)
def auth(func):
def inner(request,*args,**kwargs):
user = request.session.get(‘user‘,None)
if not user:
return redirect(‘/session_login/‘)
return func(request,*args,**kwargs)
return inner
@auth
def session_index(request):
user = request.session.get(‘user‘,None)
return render(request,‘session_index.html‘,{‘user‘:user})
@auth
def session_logout(request):
del request.session[‘user‘]
return redirect(‘/session_login/‘)
settings.py
MIDDLEWARE_CLASSES = [
‘django.middleware.security.SecurityMiddleware‘,
‘django.contrib.sessions.middleware.SessionMiddleware‘,
‘django.middleware.common.CommonMiddleware‘,
# ‘django.middleware.csrf.CsrfViewMiddleware‘,
‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
‘django.contrib.auth.middleware.SessionAuthenticationMiddleware‘,
‘django.contrib.messages.middleware.MessageMiddleware‘,
‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
]
session_login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/session_login/" method="POST">
<input type="text" name="user">
<input type="text" name="pwd">
<input type="submit" value=http://www.mamicode.com/"提交" />
</form>
</body>
</html>
session_index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>欢迎:{{ user }}登录</h1>
<a href=http://www.mamicode.com/"/session_logout/">注销
</body>
</html>
同步数据
python3 manage.py makemigrations
python3 manage.py migrate
访问
http://127.0.0.1:8000/session_login/ 用户名密码 hu/123 跳转index
Django数据库的使用(sqlite)
1,创建项目,名为sqliteTest
django-admin startproject sqliteTest
cd sqliteTest/
django-admin startapp sqTest
2,将新建的应用添加到项目下的sqliteTest文件夹中的settings.py中,告诉Django有sqTest这个应用
setting.py中有一个属性INSTALLED_APPS,将sqTest填入。
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘sqTest’
]
3,在sqTest文件夹的models中添加需要的数据的类。比如我需要一些NBA球员的数据,所以我创建一个Player类,
里面包含几个属性,分别为姓名,年龄,位置,号码。
其中,CharField表示该属性应该为一个字段,IntegerField表示该属性为一个整数。max_length表示最大长度。
models.py
class Player(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
position = models.CharField(max_length=10)
number = models.IntegerField()
4.创建表同步数据
python manage.py makemigrations
python manage.py migrate
5,终端查看
使用python manage.py shell进入命令行,之后读取Player
>>> Player.objects.all()
<QuerySet []>
>>> Player.objects.create(name="Curry", age=28, position="G", number=30)
<Player: Player object>
出现<Player: Player object>。但是此时打印出来的数据可读性不强,所以退出命令行,在model中添加一个__str__方法,增加可读性。
def __str__(self):
return self.name
此时再次进入命令行,读取Player
>>> from sqTest.models import Player
>>> Player.objects.all()
<QuerySet [<Player: Curry>]>
6,添加数据库,除了上面一种方法,还有两种方法创建。
(1)创建一个Person类的实例,给实例的属性赋值,最后使用save()方法将实例存入数据库。
>>> player = Player(name="Durant")
>>> player.age = 28
>>> player.position = "F"
>>> player.number = 35
>>> player.save()
>>> Player.objects.all()
<QuerySet [<Player: Curry>, <Player: Durant>]>
(2)使用get_or_create创建,防止重复,如果插入相同的,会失败。如果如果只用create,会使表中有两个相同的数据
>>> Player.objects.get_or_create(name="Curry", age=28, position="G", number=30)
(<Player: Curry>, False)
7,获取对象
(1),获取该数据表所有数据:
>>> Player.objects.all()
(2),get方法,只能获取一个值,如果获取的值有两个,会失败
>>> Player.objects.get(name="Durant")
<Player: Durant>
>>> Player.objects.get(age=28)
sqTest.models.MultipleObjectsReturned: get() returned more than one Player -- it
returned 2!
(3),filter筛选多个
>>> Player.objects.filter(age=28)
<QuerySet [<Player: Curry>, <Player: Durant>
Django数据库实用(sqlite)
1,创建项目,名为sqliteTest
django-admin startproject sqliteTest
cd sqliteTest/
django-admin startapp sqTest
2,将新建的应用添加到项目下的sqliteTest文件夹中的settings.py中,告诉Django有sqTest这个应用
setting.py中有一个属性INSTALLED_APPS,将sqTest填入。
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘sqTest’
]
3,在sqTest文件夹的models中添加需要的数据的类。比如我需要一些NBA球员的数据,所以我创建一个Player类,
里面包含几个属性,分别为姓名,年龄,位置,号码。
其中,CharField表示该属性应该为一个字段,IntegerField表示该属性为一个整数。max_length表示最大长度。
models.py
class Player(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
position = models.CharField(max_length=10)
number = models.IntegerField()
4.创建表同步数据
python manage.py makemigrations
python manage.py migrate
5.路由系统配置
urls.py
from sqlTest import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^showpage/‘, views.showpage), #加url访问页面
]
6.业务处理
views.py
from sqlTest import models
# Create your views here.
def showpage(request): #与url访问一致
data_list = models.Player.objects.all()
return render(request, ‘showpage.html‘, {‘data‘: data_list})
7.页面html
template/showpage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for line in data %}
<tr>
<td>{{ line.name }}</td>
<td>{{ line.age }}</td>
<td>{{ line.position }}</td>
<td>{{ line.number }}</td>
<br/>
</tr>
{% endfor %}
</body>
</html>
8.启动并访问
python manage.py runserver 0.0.0.0:8080 #允许所有
http://127.0.0.1:8000/showpage/
python day19