欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

第八章(2)

程序员文章站 2024-03-18 23:38:04
...
  1. 上传文件示例(html)
  2. fbc和cbv
  3. html获取字典(keys,values)
  4. django路由系统
  5. django路由系统(url正则表达式)
  6. django路由转发(include)
  7. django数据库
  8. django数据库字段参数
  9. 关联表
  10. request,POST.GET.FILES方法
  11. django数据库增删改查
  12. 数据库类型
  13. 循环生成***
  14. Ajax
  15. 数据库表多对多

1.上传文件示例(html)login.html

login.html

from django.shortcuts import render
import os
# Create your views here.
from django.shortcuts import HttpResponse
from django.shortcuts import render,redirect
from django.core.files.uploadedfile import InMemoryUploadedFile

def login(request):
    if request.method == "GET":
        return render(request,'login.html')
    elif request.method == "POST":
        # v = request.POST.get('gender')       获取单选
        # print(v)
        # v = request.POST.getlist('favor')    获取多选(list)
        # print(v)
        # v = request.POST.get('fafafa')
        # print(v)
        obj = request.FILES.get('fafafa')       获取文件
        print(obj,type(obj),obj.name)
        file_path = os.path.join('upload',obj.name)
        f = open(file_path,mode='wb')
        for i in obj.chunks():
            f.write(i)
        f.close()

        return render(request,'login.html')
    else:
        return redirect('/index/')

 

<body>
    <form action="/login/" method="POST" enctype="multipart/form-data"> #上传文件
        <p>
            <input type="text" name="user" placeholder="用户名" />
        </p>
        <p>
            <input type="password" name="pwd" placeholder="密码"/>
        </p>
        <p>
            男:<input type="radio" name="gender" value="1"/>
            女:<input type="radio" name="gender" value="2"/>
            二:<input type="radio" name="gender" value="3"/>
        </p>
        <p>
            男:<input type="checkbox" name="favor" value="11"/>
            女:<input type="checkbox" name="favor" value=22"/>
            二:<input type="checkbox" name="favor" value="33"/>
        </p>
        <p>
            <select name="city" multiple>         #多选
                <option value="sh">上海</option>
                <option value="bj">北京</option>
                <option value="ti">天津</option>
            </select>
        </p>
        <p>
            <input type="file" name="fafafa" />
        </p>
        <input type="submit" value="提交" />
    </form>
</body>
</html>

views.py

2.fbv&cbv

url.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from cmdb import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    url(r'login/',views.login),                            #fbv
    url(r'home/', views.Home.as_view())           #cbv
]

templates\home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/home/" method="POST">
        <input type="text" name="user"/>
        <input type="submit"/>
    </form>
</body>
</html>

cmdb\views.py

from django.views import View
class Home(View):
    def dispatch(self,request, *args, **kwargs):
       #调用父类中的dispatch
        print('before')
        result = super(Home,self).dispatch(request, *args, **kwargs)
        print('after')
        return result

    def get(self,request):
        print(request.method)
        return render(request,'home.html')

    def post(self,request):
        print(request.method,"POST")
        return render(request,'home.html')

html获取字典(keys,values)

login.html

<body>
    <ul>
        {% for k in user_dict.keys %}
            <li>{{ k }}</li>
        {% endfor %}
    </ul>
     <ul>
        {% for k in user_dict.values %}
            <li>{{ k }}</li>
        {% endfor %}
    </ul>
    <ul>
        {% for k,row in user_dict.items %}
            <li>{{ k }}-{{ row }}</li>
        {% endfor %}
    </ul>
</body>


viewa.py

USER_DICT = {
    'k1':'root1',
    'k2':'root2',
    'k3':'root3',
    'k4':'root4',
}
def index(request):
    return render(request, 'index.html',{'user_dict' : USER_DICT})

django路由系统(url正则表达式)

1,url(r'^index/',views.index),  url(r'^home/',views.Home.as_view()),

{% for k,row in user_list.items %}
	<li><a target="_blank" href="/detail/?nid={{ k }}">{{ row.name }} </a></li>
{% endfor %}


2,url(r'^detail-(\d+).html',views.detail),  

{% for k,row in user_list.items %}
	<li><a target="_blank" href="/detail-{{ k }}.html">{{ row.name }} </a></li>
{% endfor %}

url(r'^detail-(?p<nid>\d+)-(?p<uid>\d+).html', views.detail)
def detail(request, *args,kwargs):
	pass 

django路由转发(include)

对url路由关系进行命名, 以后可以根据次名生成自己想要的URL

url.py

url(r'^asd/', views.index, name='i1'),
url(r'^yug/(\d+)/(\d+)/', views.index, name='i2'),
url(r'^buy/(?p<pid>\d+)/(?p<nid>\d+)/', views.index, name='i3'),

xxx.html

{% url 'i1' %}               #asd/
{% url 'i2' 1 2 %}           #yug/1/2/
{% url 'i3' pid=1 nid=9 %}   #buy/1/9/

views(from django.urls import reverse 自动生成URL)

def func(request, *args, **kwargs):
	from diango.urls import reverse
	
	url1 = reverse('i1')                             # asd/
	url2 = reverse('i2',args=(1,2,))                 # yug/1/2/
	url3 = reverse('i3', kwargs={'pid':1, "nid": 9}) # buy/1/9/

phicomm/urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include

urlpatterns = [
    # path('admin/', admin.site.urls),
    url(r'^cmdb/', include("app01.urls")),
    url(r'^monitor/', include("app02.urls")),
]

app01/urls.py

from app01 import views
urlpatterns = [
    url(r'^login/', views.login),
]

app01/views.py

from django.shortcuts import render,HttpResponse

# Create your views here.

def login(request):
    return HttpResponse('APP01,login')

django数据库

app01/models.py

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    # id列,自增,主键
    # 用户名列,字符串类型,指定长度
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    
    生成表记录
    python manage.py makemigrations
    
    创建表
    python manage.py migrate

phicomm/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01'  ###
]

链接mysql

DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'root',
        'PASSWORD': 'XXXX',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

phicomm/init.py

import pymysql

pymysql.install_as_MySQLdb()

增删改查

phicomm/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01'
]



DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'abc',
        'USER': 'test',
        'PASSWORD': '123.com',
        'HOST': '192.168.1.6',
        'PORT': '3306',
    }
}

phicomm/urls.py
urlpatterns = [
    # path('admin/', admin.site.urls),
    url(r'^cmdb/', include("app01.urls")),
    url(r'^monitor/', include("app02.urls")),
]


app01/urls.py
from app01 import views
urlpatterns = [
    url(r'^login/', views.login),
    url(r'^orm/',views.orm),
from app01 import models
def orm(request):
    #创建
    #models.UserInfo.objects.create(username='root',password='123')

    # dic = {'username': 'test','password':'789'}
    # models.UserInfo.objects.create(**dic)

    # obj = models.UserInfo(username='zhang',password='123')
    # obj.save()

    #查
    #result = models.UserInfo.objects.all()
    # result = models.UserInfo.objects.filter(username="root",id='1')
    # for row in result:
    #     print(row.id,row.username,row.password)

    #删除
    # models.UserInfo.objects.all(id='3').delete()
    # models.UserInfo.objects.filter(id='3').delete()

    #更新
    models.UserInfo.objects.filter(id=4).update(password='6789')
    return HttpResponse('orm')  

django数据库字段参数

class UserInfo(moldels.Model):
	# id列,自增,主键
	# 用户名列,字符串类型,指定长度
	# 字符串,数字,时间,二进制
	username = models.CharField(max_length=32)
	password = models.CharField(max_length=60)
	email = models.CharField(max_length=60)
	test = models.EmailField(max-length=19,null=True)
	#test = models.URLField(max-length=19,null=True)
	#test = models.GenericIPAddressField()
null                数据库中字段是否可以为空
    db_column           数据库中字段的列名
    db_tablespace
    default             数据库中字段的默认值
    primary_key         数据库中字段是否为主键
    db_index            数据库中字段是否可以建立索引
    unique              数据库中字段是否可以建立唯一索引
    unique_for_date     数据库中字段【日期】部分是否可以建立唯一索引
    unique_for_month    数据库中字段【月】部分是否可以建立唯一索引
    unique_for_year     数据库中字段【年】部分是否可以建立唯一索引

    verbose_name        Admin中显示的字段名称
    blank               Admin中是否允许用户输入为空
    editable            Admin中是否可以编辑
    help_text           Admin中该字段的提示信息
    choices             Admin中显示选择框的内容,用不变动的数据放在内存中从而避免跨表操作
                        如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1)

    error_messages      自定义错误信息(字典类型),从而定制想要显示的错误信息;
                        字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date
                        如:{'null': "不能为空.", 'invalid': '格式错误'}

    validators          自定义错误验证(列表类型),从而定制想要的验证规则
                        from django.core.validators import RegexValidator
                        from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\
                        MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
                        如:
                            test = models.CharField(
                                max_length=32,
                                error_messages={
                                    'c1': '优先错信息1',
                                    'c2': '优先错信息2',
                                    'c3': '优先错信息3',
                                },
                                validators=[
                                    RegexValidator(regex='root_\d+', message='错误了', code='c1'),
                                    RegexValidator(regex='root_112233\d+', message='又错误了', code='c2'),
                                    EmailValidator(message='又错误了', code='c3'), ]
                            )

参数
null              是否可以为空
default           默认值
primary_key       主键
db_column         列名
db_index          索引
unique            唯一索引
unique_for_date   
unique_for_month
unique_for_year
auto_now           自动生成时间
auto_now_add       创建时自动生成时间

    obj = UserGroup.objects.filter(id=1).update(caption='CEO')
    obj = UserGroup.objects.filter(id=1).first()
    obj.caption="CEO"
    obj.save()

choices              django admin中显示下拉框,避免链表查询
blank                django admin是否可以为空
verbose_name         django admin显示字段中文
editable			django admin是否可以被编辑
error_messages		 错误信息
help_text            django admin提示
validators           django admin自定义错误信息
class UserInfo(moldels.Model):
	# id列,自增,主键
	# 用户名列,字符串类型,指定长度
	# 字符串,数字,时间,二进制
	username = models.CharField(max_length=32)
	password = models.CharField(max_length=60)
	email = models.CharField(max_length=60)
	test = models.EmailField(max-length=19,null=True,error_messages={'invalid':'请输入密码'})
	
	user_type_choices = (
		(1,'超级用户'),
		(2,'普通用户'),
		(3,'低级用户'),
		
	)
	user_type_id = models.IntegerField(choices=user_type_choices,default=1)
	
	
user_list = Userinfo.objects.all()
for row in user_list:
	print(row.user_group_id)
	print(row.user_group.uid)

9.关联表

from django.db import models

# Create your models here.

class UserGroup(models.Model):
    uid = models.AutoField(primary_key=True)
    groupname = models.CharField(max_length=32)

class UserInfo(models.Model):
    # id列,自增,主键
    # 用户名列,字符串类型,指定长度
    username = models.CharField(max_length=32,blank=True,verbose_name='用户名')
    password = models.CharField(max_length=32)


    # user_group = models.ForeignKey(UserGroup,to_field='uid',default=1)
    user_group_id = models.ForeignKey(to=UserGroup,to_field='uid',on_delete=models.CASCADE)

10.request,POST.GET.FILES方法

request.POST.get
request.GET.get
request.FILES.get()   获取文件

#checkbox,
.........getlist()

request.path_info 

文件对象 = request.FILES.get()
文件对象. name
文件对象. size
文件对象. chunks()

#<form 特殊的设置></form> 

11.django数据库增删改查

增
models.User.objects.create(name='qiansanwan',age=18)
dic = {'name':'xx', 'age': 19}
midels.User.objects.create(**dic)

  obj = models.User(name='qiansanwan',age=18)
  obj.save()

删
	   models.User.objects.filter(id=1).delete()
改
       moldes.User.objects.filter(id__gt=1).update(name='zhang',age=18)
       dic = {'name': 'xx','age': 19}
       models.User.objects.filter(id__gt=1).update(**dic)
查
      moldes.User.objects.filter(id=1,name='root')
      moldes.User.objects.filter(id__gt=1,name='root')      大于
      moldes.User.objects.filter(id__lt=1)                  小于
      moldes.User.objects.filter(id__gte=1)                 大于等于
      moldes.User.objects.filter(id__lte=1)                 小于等于
      
      moldes.User.objects.filter(id=1,name='root')
      dic={'name':'xx','age_gt': 19}
      moldes.User.objects.filter(**dic)

12.数据库类型

v1 = models.Business.objects.all()
#QuerySet ,内部元素都是对象

#QuerySet ,内部元素都是字典
v1 = models.Business.objects.all().values('id','caption')

#QuerySet ,内部元素都是元组
v1 = models.Business.objects.all().values_list('id','caption')

#获取到的一个对象,如果不存在就报错
models.Business.objects.get(id=1)
对象或者None = models.Business.objects.filter(id=1).first()

13.循环生成***

{% for row in v1%}
	<td>{{forloop.counter}} <td/>
{% endfor %}

14.Ajax

$.ajax({
    url: '/host',
    type: "POST",
    data: {'K1': 123,'K2': 'root'},
    success: function(data){
    	//data是服务器端返回的字符串
    	var obj = JSON.parse(data);
    }
})

建议:永远让服务器端返回一个字典

return HttpResponse(json.dumps(字典))

15.数据库表多对多

class Host(models.Model):
	nid = models.AutoField(primary_key=True)
	hostname = models.CharField(max_length=32,db_index=True)
	ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
	port = models.IntegerField()
	b = models.ForeignKey(to="Business", to_field='id')
	
class Application(models.Model):
	name = models.CharField(max_length=32)
	
class HostToApp(models.Model):
	hobj = models.ForeignKey(to=’Host‘,to_field='id')
    aobj = models.ForeignKey(to='Application','to_field='id')
    
class Host(models.Model):
	nid = models.AutoField(primary_key=True)
	hostname = models.CharField(max_length=32,db_index=True)
	ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
	port = models.IntegerField()
	b = models.ForeignKey(to="Business", to_field='id')
	

class Application(models.model):
	name = models.CharField(max_length=32)
	r = models.ManyToManyField("Host")
	

无法直接对第三张表直接进行操作

obj = Application.objects.get(id=1)
obj.name

第三张表操作
obj.r.add(1)
obj.r.add(2)
obj.r.add(2,3,4)
obj.r.add(*[1,2,3])

obj.r.remove(1)
obj.r.remove(2,4)
obj.r.remove(*[1,2,3])

设置只保留3,5,7
obj.r.set([3,5,7])