DJango小總結一
views.py
def func(request):
# 包含所有的請求數據
...
return HttpResponse(‘字符串‘)
return render(request, ‘index.html‘, {‘‘})
retrun redirect(‘URL‘)
模板語言
return render(request, ‘index.html‘, {‘li‘: [11,22,33]})
{% for item in li %}
<h1>{{item}}</h1>
{% endfor %}
路由系統,URL
1、url(r‘^index/‘, views.index),
url(r‘^home/‘, views.Home.as_view()),
2、url(r‘^detail-(\d+).html‘, views.detail),
3、url(r‘^detail-(?P<nid>\d+)-(?P<uid>\d+).html‘, views.detail)
PS:
def detail(request, *args,**kwargs):
pass
實戰:
url(r‘^detail-(\d+)-(\d+).html‘, views.detail),
根據名稱生成url
from django.urls import reverse
url(r‘^asdfasdfasdf/‘, views.index, name=‘i1‘),
url1 = reverse(‘i1‘) # asdfasdfasdf/
url(r‘^yug/(\d+)/(\d+)/‘, views.index, name=‘i2‘),
url2 = reverse(‘i2‘, args=(1,2,)) # yug/1/2/
url(r‘^buy/(?P<pid>\d+)/(?P<nid>\d+)/‘, views.index, name=‘i3‘),
url3 = reverse(‘i3‘, kwargs={‘pid‘: 1, "nid": 9}) # buy/1/9/
xxx.html
{% url "i1" %} # asdfasdfasdf/
{% url "i2" 1 2 %} # yug/1/2/
{% url "i3" pid=1 nid=9 %} # buy/1/9/
# 當前的URL
request.path_info
視圖
1、獲取用戶請求數據
request.GET
request.POST
request.FILES
PS:
GET:獲取數據
POST:提交數據
2、checkbox等多選的內容
request.POST.getlist()
3、上傳文件
# 上傳文件,form標簽做特殊設置
obj = request.FILES.get(‘fafafa‘)
obj.name
f = open(obj.name, mode=‘wb‘)
for item in obj.chunks():
f.write(item)
f.close()
ORM操作
select * from tb where id > 1
# 對應關系
models.tb.objects.filter(id__gt=1)
models.tb.objects.filter(id=1)
models.tb.objects.filter(id__lt=1)
創建類
a. 先寫類
from django.db import models
# app01_userinfo
class UserInfo(models.Model):
# id列,自增,主鍵
# 用戶名列,字符串類型,指定長度
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
b. 註冊APP
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘app01‘,
]
c. 執行命令
python manage.py makemigrations
python manage.py migrate
註:
Django默認使用MySQLdb模塊鏈接MySQL
主動修改為pymysql,在project同名文件夾下的__init__文件中添加如下代碼即可:
import pymysql
pymysql.install_as_MySQLdb()
字段的參數:
null -> db是否可以為空
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 form ,自定義錯誤信息(欠)
創建 Django 用戶:python manage.py createsuperuser
根據類對數據庫表中的數據進行各種操作
一對多:
a. 外檢
b.
外鍵字段_id
c.
models.tb.object.create(name=‘root‘, user_group_id=1)
d.
userlist = models.tb.object.all()
for row in userlist:
row.id
row.user_group_id
row.user_group.caption
DJango小總結一