首页 > 代码库 > python学习第十九天
python学习第十九天
Django
获取一个项目的多个数据 request.POST.getlist(‘favor‘)
上传文件
import os
obj =request.FILES.get(‘‘)
file_path =os.path.join(‘upload‘,obj.name)
with open(file_path,‘wb‘) as f:
for i in obj.chunks():
f.write(i)
FBV function base view
CBV class base view
url对应关系 url(r‘^up‘, views.Up.as_view())
from django.views import View
class Up(View):
def dispatch(self, request, *args, **kwargs):
print(‘before‘)
result =super(Up,self).dispatch(request, *args, **kwargs) 继承父类的dispatch方法,dispatch方法负责识别用户数据发送方式
print(‘after‘)
return result
def get(self,request):
return render(request, ‘upload.html‘)
def post(self,request):
obj = request.FILES.get(‘file‘)
file_path = os.path.join(‘upload‘, obj.name)
with open(file_path, ‘wb‘) as f:
for i in obj.chunks():
f.write(i)
return render(request, ‘upload.html‘)
模板语言循环字典
{% for row in user_dict.keys(.values;.items) %} .keys .values .items 循环列表元素,一个参数循环时以元组形式返回,两个参数循环时分别对两个参数赋值
{% endfor %}
Django正则URL
URL动态对应
url(r‘^detail-(\d+).html‘, views.detail) 顺序赋值
url(r‘^detail-(?p<nid>\d+)-(?p<uid>\d+).html‘, views.detail) 固定赋值
url(r‘^index‘, views.Index,name=‘index‘)
<form action="{% url ‘index‘ %}"></form> 自动对应URL
<form action="{% url ‘index‘ 3 %}"></form> 跳转到指定URL
<form action="{% url ‘index‘ nid=3 %}"></form> 跳转到指定URL
<form action="{{request.path_info}}"></form> 自动对应URL
from django.urls import reverse
v =reverse(‘index‘,args=(90,)) 生成指定url
v =reverse(‘index‘,kwargs=(‘nid‘=90,)) 生成指定url
URL分发
from django.conf.urls import include
url(r‘^cmdb/‘, include("cmdb.urls")) 先匹配url中的cmdb,然后在cmdb的urls文件中匹配对应函数
Django连接Mysql
DATABASES ={‘default‘:{‘ENGINE‘:‘django.db.backends.mysql‘,‘NAME‘:‘dbname‘,‘USER‘:‘root‘,‘PASSWORD‘:‘‘,‘HOST‘:‘‘,‘PORT‘:‘‘,}}
python3中需要在django的app目录下的__init__.py文件中添加如下两行代码
import pymysql
pymysql.install_as_MySQLdb()
创建表
class UserInfo(models.Model):
username =models.CharField(max_length=32)
password =models.CharField(max_length=64)
添加数据
1 models.UserInfo.objects.create(username=‘root‘,password=‘123‘)
2 dict ={‘username‘:‘jack‘,‘password‘:‘123‘}
models.UserInfo.objects.create(**dict)
3 obj =models.UserInfo(username=‘root‘,password=‘123‘)
obj.save()
查询
models.UserInfo.objects.all() 获取表中所有数据
models.UserInfo.objects.filter(条件,条件)
删除
models.UserInfo.objects.filter(条件,条件).delete()
修改
models.UserInfo.objects.filter(条件,条件).update(password=‘123’)
django ORM字段类型以及参数
http://www.cnblogs.com/wupeiqi/articles/5246483.html
user_type_choices =((1,‘超级用户‘),(2,‘普通用户‘),)
user_type_id =models.ItegerField(choices=user_type_choices)
添加外键
user_group =models.ForeignKey("UserGroup",to_filed=‘uid‘)
python学习第十九天