worken name
django-admin startproject mysite
挂梯子
pip install pillow -i https://pypi.python.org/simple
建一个utf8的数据库
create database script DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
链接数据库
jdbc:mysql://localhost:3306/DjangoCache2?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
C:\ProgramData\MySQL\MySQL Server 8.0\Data
1. mysqldump -uroot -p123456 djangocache2> test.sql 将数据库导出成sql文件
https://www.runoob.com/mysql/mysql-database-export.html
1.create database test;
2. use test
3.source c: path 将生成的sql 文件重新导成数据库文件
"""
Django settings for DjangoModel project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'r!5&+zz!+po%ni!cq!!f@ps#osgpdy5^u95&zxwqde*^4_j^g#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'App',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 注释掉使用POST表单
# 防跨站攻击
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 中间键的注册
# 'middleware.LearnMiddle.HelloMiddle',
]
ROOT_URLCONF = 'DjangoModel.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'DjangoModel.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'HOST' :'127.0.0.1',
'PORT' : '3306',
'NAME' :'DjangoModel',
'USER' :'root',
'PASSWORD':'123456',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
#不使用系统时区
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
ipconfig
python manage.py runserver 0.0.0.0:8000
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
APPEND_SLASH = False
MEDIA_ROOT=os.path.join(BASE_DIR,'static/upload')
s_grade = models.ForeignKey(Grade, on_delete=models.CASCADE)
{% csrf_token %}
url(r'App/',include(('App.urls','App'),namespace='App')),
url('Two/', include(('Two.urls', 'second'), namespace='second')),
url(r'^lean/',views.lean,name='lean')
def lean(request):
return HttpResponse('Love Lean')
<a href="{% url 'second:lean' %}">Go Lean</a>
<a href="{% url 'second:get_time' 15 38 42%}">Time Time</a>
<a href="{% url 'namespace:name' value1 value2 value3 %}">Data</a>
# (?P\d+)
# (?P\d+)
# (?P\d+)
url(r'^GetData/(?P\d+)/(?P\d+)/(?P\d+)' ,views.get_data)
def get_data(request, day, mouth, year):
return HttpResponse(f'今天时{year}年{mouth}月{day}日')
<a href="{% url 'second(namespace):data(name)' day=26 mouth=5 year=2020 %}">Data</a>
<a href="{% url 'namespace:name' key1=value1 %}">Data</a>
print(request.GET)
#
hobbys=request.GET.getlist('hobby')
print(hobbys)
#['eat', 'game']
hobby=request.GET.get('hobby')
#只获得最后一个参数
#game
ip = request.META.get('REMOTE_ADDR')
def get_ticket(request):
url=reverse('App:hello') # namespace:name
return HttpResponseRedirect(url)
# return HttpResponseRedirect('/App/hello/')
def get_ticket(request):
return redirect(reverse('App:hello'))
reverse('namespace:name',args=(value1,value2,))
reverse('namespace:name',kwargs={ky1:value1,key2:value2})
301
302
400
403
404
405
500
def get_info(request):
data={
'status':200,
'msg':'ok',
}
return JsonResponse(data=data)
# 编码
uname = parse.quote(request.POST.get('uname'))
# 解码
uname = parse.unquote(request.COOKIES.get('uname'))
加密解密使用同一个密钥(salt)
加密
# 'test'为加密解密所需要的密钥
response.set_signed_cookie('content',uname,'test')
uname=request.get_signed_cookie('content',salt='test')
# 数据库中的数据未删除
response.delete_cookie('sessionid')
# 数据库中的数据未删除
del request.session['username']
# 数据库中的数据也被删除
request.session.flush()
# 加入外键 on_delete=models.CASCADE
# null=True 可不可以为空
id_person = models.OneToOneField(Person, on_delete=models.CASCADE, null=True, blank=True)
# 加入外键 on_delete
id_person = models.ForeignKey()
class Customer(models.Model):
c_name = models.CharField(max_length=16)
class Goods(models.Model):
g_name = models.CharField(max_length=16)
g_customer = models.ManyToManyField(Customer)
# Per
class Person(models.Model):
p_name = models.CharField(max_length=16, db_column='name')
# True 为男性
p_sex = models.BooleanField(default=True)
class IDCard(models.Model):
id_number = models.IntegerField(max_length=18, unique=True)
id_person = models.OneToOneField(Person, on_delete=models.CASCADE, null=True, blank=True)
on_delete 在删除数级联的数据如何处理
默认特性CASCADE
#参数 on_delete=models.CASCADE
PROTECT受保护的
# 参数 on_delete=models.PROTECT
SET_NULL(前提允许为NULL)
# 将主表中的name被删除后从表级联的id_person_id成为 null
id_person = models.OneToOneField(Person, on_delete=models.SET_NULL, null=True, blank=True)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G4EwykBr-1640748463636)(./png/Django1.png)]
SET_DEFAULT (存在默认值)
SET(指定值)
from django.db import models
class Person(models.Model):
# 主表
p_name = models.CharField(max_length=16, db_column='name')
# True 为男性
p_sex = models.BooleanField(default=True)
class IDCard(models.Model):
# 从表
id_number = models.IntegerField(max_length=16, unique=True)
id_person = models.OneToOneField(Person, null=True, blank=True, on_delete=models.SET_NULL)
def get_person(request):
idcard = IDCard.objects.last()
person = idcard.id_person
return HttpResponse(f'{person.p_name}')
# idcard 为隐性属性名
def get_idcard(request):
person = Person.objects.last()
idcard = person.idcard
return HttpResponse(f'{idcard.id_number}')
默认继承是将通用字段放到父表中,特定字段放到自己的表中,中间使用外键联接
使用元信息来解决这个问题
class Animal(models.Model):
a_name = models.CharField(max_length=16)
class Meta:
# 只创建Cat和Dog两张表
# 如果不加 创建三张表 如果主表数据量大将影响数据的查询速度
abstract = True
class Cat(Animal):
c_eat = models.CharField(max_length=32)
class Dog(Animal):
d_lags = models.IntegerField(default=4)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YjnATMrr-1640748463637)(.\png\Django2.png)]
python manage.py inspectdb
将用命令生成的python代码拷贝到App的models中
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MtcgrMob-1640748463638)(.\png\Django3.png)]
python manage.py inspectdb > App/models.py
元信息中包含一个属性managed=False
如果自己的模型不想被迁移系统管理可增加属性managed=False
def upload_file(request):
if request.method=='GET':
return render(request,'upload.html')
elif request.method=='POST':
icon=request.FILES.get('icon')
print(icon)
print(type(icon))
with open(r'D:\my_projects\SqlToModel\static\img\icon.png','wb') as file:
for part in icon.chunks():
file.write(part)
file.flush()
return HttpResponse('Files upload Success!')
@ file name: image_field.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传title>
head>
<body>
<form action="{% url 'app:upload_file' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<span>文件: span>
<input type="file" name="icon">
<br>
<input type="submit" value="上传">
form>
body>
html>
class UserModel(models.Model):
u_name = models.CharField(max_length=16)
# upload_to 相对路径 相对于的是MEDIA_ROOT 媒体根目录
u_icon = models.ImageField(upload_to='%Y/icons')
def image_field(request):
if request.method == 'GET':
return render(request, 'image_field.html')
elif request.method == 'POST':
username = request.POST.get('username')
icon = request.FILES.get('icon')
user = UserModel()
user.u_name = username
user.u_icon = icon
user.save()
return HttpResponse('upload Success!')
{% extends 'base.html' %}
{% load static %}
{% block rander %}
<h1>testh1>
{% endblock %}
{% block link_css %}
{# 只是开发者可用#}
{% endblock %}