Django's configuration file, add or delete pycharm and django connect to the database, create tables and table change search

 After you create a project file folder configuration

When you create a project with pycharm> settings to customize an app name, to help you automatically create an application, and automatically create a template folder, view the configuration INSTALLED_APPS does not automatically add the new app, if not manually add, TEMPLATES list "DIRS" If did not add path templates folder, add it manually.

Log Function
1. Route L (R & lt 'Login ^ /', views.login) , if not access slash slash internal routing automatically redirected

all

2. All front-end browser rendered pages are written in html file back end, these files are written in the default templates folder;

3. All static files (css, js, front-end third-party libraries) are placed in static default folder

html page the way the introduction of external resources
1) CDN
2) Local

Static configuration file

STATIC_URL = '/ static /'
static configuration files, be exposed to the outside world can still access the server folder below all the resources
STATICFILES_DIRS = [
os.path.join (base_dir, 'static')]

STATIC_URL = '/ static /' # interfaces prefix (each html incoming links prefix in the document template folder) with little relation name of your static folders are not, this prefix by default with a static folder name as !
html file template in import JQuery, css, js links to static folder prefix will find the corresponding import file,

Static configuration file
STATICFILES_DIRS = [
os.path.join (base_dir, 'static'), # is your static folder path
os.path.join (base_dir, 'static1'),
os.path.join (base_dir, 'static2 ')]

ps: incoming links within html file prefix will in turn find the list of all the static file path is linked with their match (if there is a path to the file prefix static) to find the words to stop immediately return a 404 not found

form Form Review

form Form trigger action are two ways to submit data

<input type="submit">
<button></button>

orm targeting address data submitted
action filed address attribute control
1. The full path

<form action="http://127.0.0.1:8000/login/",method="post"> # method不写默认是get请求

Into a post request, remember the settings in the configuration file middleware written off. Otherwise newspaper Yellow Pages

2. Write only the path suffix

<form action="/login/">

3. Do not write (default submission to the current path)

The default is to get a request form form

Depending on the mode of the request, and returns information on the front end

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
    <script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">
    <div class="'row">
        <h1 class="text-center">登录页面</h1>
        <div class="col-md-6 col-md-offset-3">
            <form action="" method="post">
                <p>username:<input type="text" class="form-control" name="username"></p>
                <p>username:<input type="text" class="form-control" name="username"></p>
                <p>username:<input type="text" class="form-control" name="username"></p>
                <p>password:<input type="password" class="form-control" name ="password"></p>
                <input type="submit" class="btn btn-success">
            </form>
        </div>
    </div>
</div>
</body>
</html>
根据客户端请求方式的不同执行不同的逻辑代码
from django.shortcuts import render,HttpResponse

# Create your views here.
def login(request):
    # print(request)   # request:<WSGIRequest: GET '/login/'>

    # print(request.method)  # 获取的是用户的请求方式,是全大写的字符串
    if request.method == "POST":
        print(request.POST)  # 你就把它当成一个大字典里面存放了客户端post提交的所有的数据
        # <QueryDict: {'username': ['zhang'], 'password': ['123']}>
        print(request.POST.get('username'))  # value虽然是个列表但是获取value的时候拿到却是单个元素
        # 默认只会取value列表里面的最后一个元素
        # <QueryDict: {'username': ['zhang', 'li', 'zhao'], 'password': ['1234']}>

        # 一次性获取value列表里面所有的数据需要用getlist()
        print(request.POST.getlist('username'))  # ['zhang', 'li', 'zhao']
        print(request.POST['password'])  # 不推荐使用该方法获取数据
        return HttpResponse('登录成功!')

    return render(request,'login.html')
'''
获取value列表里面所有的元素需要使用getlist  应用场景:用户的爱好 多选框get只会获取到value列表的最后一个元素
'''
  # print(request.environ)
    '''
{'ALLUSERSPROFILE': 'C:\\ProgramData',
'APPDATA': 'C:\\Users\\Administrator\\AppData\\Roaming',
'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files',
'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files',
'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files',
'COMPUTERNAME': 'WIN-KIJ962UBO3B',
'COMSPEC': 'C:\\windows\\system32\\cmd.exe',
'DJANGO_SETTINGS_MODULE': 'day52.settings',
'FP_NO_HOST_CHECK': 'NO', 
'HOMEDRIVE': 'C:',
'HOMEPATH': '\\Users\\Administrator', 
'LOCALAPPDATA': 'C:\\Users\\Administrator\\AppData\\Local', 
'LOGONSERVER': '\\\\WIN-KIJ962UBO3B',
'NUMBER_OF_PROCESSORS': '4',
'OS': 'Windows_NT', 
'PATH': 'G:\\python36;G:\\python36\\Scripts;G:\\Python27;G:\\Python27\\Scripts;G:\\Python27\\Scripts;G:\\python36\\Scripts;C:\\windows\\system32;C:\\windows;C:\\windows\\System32\\Wbem;C:\\windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Users\\Administrator\\Desktop\\new 1.py;G:\\sub3;G:\\MYSQL\\bin;G:\\Git\\cmd;G:\\Git\\mingw64\\bin;G:\\Git\\usr\\bin;G:\\python36\\lib\\site-packages\\numpy\\.libs;G:\\python36\\lib\\site-packages\\numpy\\.libs', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 69 Stepping 1, GenuineIntel',
'PROCESSOR_LEVEL': '6',
'PROCESSOR_REVISION': '4501',
'PROGRAMDATA': 'C:\\ProgramData',
'PROGRAMFILES': 'C:\\Program Files',
'PROGRAMFILES(X86)': 'C:\\Program Files (x86)',
'PROGRAMW6432': 'C:\\Program Files', 
'PSMODULEPATH': 'C:\\windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\',
'PUBLIC': 'C:\\Users\\Public',
'PYCHARM_HOSTED': '1',
'PYCHARM_MATPLOTLIB_PORT': '49203',
'PYTHONIOENCODING': 'UTF-8', 
'PYTHONPATH': 'G:\\PyCharm 2018.1.4\\helpers\\pycharm_matplotlib_backend;G:\\Python代码日常\\day52'
'PYTHONUNBUFFERED': '1',
'SESSIONNAME': 'Console',
'SYSTEMDRIVE': 'C:', 
'SYSTEMROOT': 'C:\\windows',
'TEMP': 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp',
'TMP': 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp',
'USERDOMAIN': 'WIN-KIJ962UBO3B',
'USERNAME': 'Administrator',
'USERPROFILE': 'C:\\Users\\Administrator',
'WINDIR': 'C:\\windows',
'WINDOWS_TRACING_FLAGS': '3',
'WINDOWS_TRACING_LOGFILE': 'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log',
'RUN_MAIN': 'true',
'SERVER_NAME': 'WIN-KIJ962UBO3B', 
'GATEWAY_INTERFACE': 'CGI/1.1',
'SERVER_PORT': '8000', 
'REMOTE_HOST': '', 
'CONTENT_LENGTH': '', 
'SCRIPT_NAME': '', 
'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SOFTWARE': 'WSGIServer/0.2',
'REQUEST_METHOD': 'GET', 
'PATH_INFO': '/login/', 
'QUERY_STRING': '',
'REMOTE_ADDR': '127.0.0.1',
'CONTENT_TYPE': 'text/plain',
'HTTP_HOST': '127.0.0.1:8000', 
'HTTP_CONNECTION': 'keep-alive', 
'HTTP_UPGRADE_INSECURE_REQUESTS': '1',
'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate,
br', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9,en;q=0.8',
'HTTP_COOKIE': 'csrftoken=YN8zgrVrZ4rrIZpWwFmyKY6yp2ggTCaUsDT4HJYUn36OY7Ijk7LpGTHtKbNML8EB',
'wsgi.input': <_io.BufferedReader name=656>,
'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>,
'wsgi.version': (1, 0), 'wsgi.run_once': False,
'wsgi.url_scheme': 'http',
'wsgi.multithread': True, 
'wsgi.multiprocess': False,
'wsgi.file_wrapper': <class 'wsgiref.util.FileWrapper'>}
    '''

pycharm MYSQL database connection

Directly on the map:

Can be achieved with the data in the database is updated simultaneously deleted;

Django connection configuration database MYSQL

settings>DATABASES

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.sqlite3',        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),    }}

    django连接数据库
    1.需要修改配置文件
    
# 修改为:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': 'day54',
                'HOST':'127.0.0.1',
                'PORT':3306,
                'USER':'root',
                'PASSWORD':'123'
            }
        }
        ps:键必须都是大写
            
2.告诉django用pymysql替换它默认mysqldb模块连接数据库
        方式1:在你的项目文件夹下面的__init__.py
        方式2:也可以在你的应用文件夹下面的__init__.py
        
        # 固定写法
        import pymysql
        pymysql.install_as_MySQLdb()  # 告诉django用pymysql代替mysqldb连接数据库

Django's ORM

What is ORM?

Relational Mapping Object
Class "" "Table
" "object" table record
attribute "object", "a field value corresponding to a record

The django orm can not automatically help you create a library, but can help you automatically create a table
Tip: a django project on the use of a library, do not use a multiple django project library

from django.db import models

# Create your models here.
class User(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=16)  

Database migration command

The following command cmd terminal knock

# 数据库迁移(同步)命令(******)
python3 manage.py makemigrations  # 将你的数据库变动记录到一个小本本上(并不会帮你创建表)
python3 manage.py migrate         # 将你的数据库变动正在同步到数据库中

Guess you like

Origin www.cnblogs.com/zhangchaocoming/p/11921184.html