如何动态引用js文件:
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,"static"), )
方法一:
{% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>ssssss</h1> <script src="{% static "js/jquery-3.1.1.js" %}"></script> </body> </html>
方法二(1.7版本可行):
1.setting.py中的TEMPLATES节点中增加 'django.core.context_processors.static'
2.<script src="{{ STATIC_URL }}/js/jquery-3.1.1.js"></script>
Form生成动态select标签
对于类中没用"self."装饰的变量是类的静态属性,当程序生成之后,静态属性加载到内存之后变不在改变,声明类,便调用类的构造方法(__init__),若类中没用构造方法,则默认调用父类的。
1 from django import forms 2 import json 3 class ImportForm(forms.Form): 4 HOST_TYPE_LIST=( 5 (1,'物理机'), 6 (2,'虚拟机') 7 ) 8 host_type = forms.IntegerField( 9 widget=forms.Select(choices=HOST_TYPE_LIST) 10 ) 11 hostname = forms.CharField() 12 admin = forms.IntegerField( 13 widget=forms.Select() 14 ) 15 def __init__(self,*args,**kwargs): 16 #调用父类的构造函数 17 super(ImportForm,self).__init__(*args,**kwargs) 18 f = open('db_admin') 19 data = f.read() 20 data_tuple = json.loads(data) 21 self.fields['admin'].widget.choices = data_tuple
生成数据库的操作:
python manage.py makemigrations
python manage.py migrate
创建admin的账号密码:python manage.py createsuperuser
字段:
1 class UserInfo(models.Model): 2 # nid = models.AutoField() #自增列(默认有) 3 name = models.CharField(max_length=32) 4 ctime = models.DateTimeField(auto_now=True) #当前时间 5 uptime = models.DateTimeField(auto_now_add=True) #更新时间 6 7 email = models.EmailField(max_length=32,null=True) 8 email2 = models.EmailField(max_length=32,default="123@qq.com") 9 10 ip = models.GenericIPAddressField(protocol="ipv4",null=True,blank=True) 11 img = models.ImageField(null=True,blank=True,upload_to="up_load") 12 13 #输出对象时自动调用该方法 14 def __unicode__(self): 15 return self.name
字段参数:
blank diango的admin中添加数据时可否允许空值
null 数据库字段中是否可以为空
primary_key = False 主键,对AutoField设置主键后,就会替代原来的自增id列
choices:(一般用于下拉框)
default: 默认值
verbose_name Admin中字段的显示名称
name|db_colum 数据库中的字段名称
unique = True 不允许重复
db_index = True 数据库索引
editable 在admin里是否可编辑
error_messages = None 错误提示
validators = []
form表单之文件上传:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 {# 上传文件时,必须要有enctype="multipart/form-data"#} 9 <form action="/upload/" method="post" enctype="multipart/form-data"> 10 <p><input type="file" name="f1"/></p> 11 <p><input type="file" name="f2"/></p> 12 <p><input type="text" name="hostname"/></p> 13 <input type="submit" value="Upload"/> 14 </form> 15 </body> 16 </html>
1 def upload(request): 2 if request.method == "POST": 3 inp_post = request.POST 4 inp_files = request.FILES 5 file_obj1 = inp_files.get('f1') 6 f = open(file_obj1.name,'wb') 7 for line in file_obj1.chunks(): 8 f.write(line) 9 f.close() 10 print inp_post 11 print file_obj1,type(file_obj1) 12 return render(request,'home/upload.html')
增:
models.Tb1.objects.create(c1='xx',c2='oo')
obj = models.Tb1(c1='xx',c2='oo')
obj.save()
dic = {'c1':'xx','c2':'oo'}
models.Tb1.objects.create(**dic)
查:
models.Tb1.objects.get(id=123) #不存在抛异常
models.Tb1.objects.all()
models.Tb1.objects.filter(name='seven') #参数也支持字典
models.Tb1.objects.all().first() #获取第一条数据
models.Tb1.objects.all().values('username') #获取指定列的数据(字典)
models.SimpleModel.objects.all().values_list('username')#获取指定列的数据(列表)
删:
models.Tb1.objects.filter(name='seven').delete()
改:
models.Tb1.objects.filter(name='seven').update(gender='0')
obj = models.Tb1.objects.get(id=1)
obj.c1 = '111'
obj.save()
其他:
1 models.SimpleModel.objects.filter(id_gt=1) #大于1 2 models.SimpleModel.objects.filter(id_lt=10) #小于10 3 models.SimpleModel.objects.filter(id_lt=10,id_gt=1) 4 5 models.SimpleModel.objects.filter(id_in=[11,22,33]) #id等于11,22,33 6 models.SimpleModel.objects.exclude(id_in=[11,22,33]) #id不等于11,22,33 7 8 models.SimpleModel.objects.filter(username__contains='ven') #包含 9 models.SimpleModel.objects.filter(username__icontains='ven') #包含(大小写不敏感) 10 models.SimpleModel.objects.exclude(username__icontains='ven') #不包含(大小写不敏感) 11 12 models.SimpleModel.objects.filter(id_range=[1,2]) #范围 13 14 # 其他:startswith,istartswith,endswith,iendswith 15 16 models.SimpleModel.objects.filter(username='senven').order_by('id') #asc 升序 17 models.SimpleModel.objects.filter(username='senven').order_by('-id') #desc 降序 18 19 models.SimpleModel.objects.all()[10,20] #分页 20 21 from django.db.models import Count,Min,Max,Sum 22 models.SimpleModel.objects.filter(c1=1).values('id').annotate(c=Count('num'))
例子:
1 from django.shortcuts import HttpResponse,render 2 from app01 import models 3 from app01.forms import forign as ForignForm 4 5 def create_user_group(request): 6 models.UserGroup_New.objects.create(caption='CSO') 7 # models.UserGroup_New.objects.create(caption='CEO') 8 # models.UserGroup_New.objects.create(caption='CTO') 9 # models.UserGroup_New.objects.create(caption='COO') 10 return HttpResponse('ok') 11 12 def create_user(request): 13 obj = ForignForm.UserForm(request.POST) 14 if request.method == "POST": 15 if obj.is_valid(): 16 all_data = obj.clean() 17 print all_data 18 #方法1 19 # group_obj = models.UserGroup_New.objects.get(id=all_data['user_group']) 20 # models.User_New.objects.create(username=all_data['username'],user_group=group_obj) 21 #方法2 22 #models.User_New.objects.create(username=all_data['username'], user_group_id=all_data['user_group']) 23 models.User_New.objects.create(**all_data) 24 25 else: 26 pass 27 # val = request.GET.get('username') 28 # user_list = models.User_New.objects.filter(username=val) 29 val = request.GET.get('user_group') 30 user_list = models.User_New.objects.filter(user_group__caption=val) 31 #user_list = models.User_New.objects.all() 32 return render(request,"forign/create_user.html",{'obj':obj,'user_list':user_list})