Simple django project implementation analysis

Static configuration file

Brief introduction

What is a static file?

  django project introduced by third-party packages, js, css, write their own js, css, save pictures and other relevant data

Why To configure a static file?

  Browser html page to get through the path we import third-party libraries, initiated the request, django is open only for interface resources (url control), can request, our static files by default is not open request, a static configuration file is open to external files can access resources inside a folder, so that external direct access.

Configuration

  1 of static default all files in the static folder

    Put all the files in this folder

  2 To configure the setting in

= STATICFILES_DIRS [ 
the os.path.join (base_dir, 'static'), can be placed inside # plurality of folders
]

note:

"" " 
1 static folder is the default put everyone unified file static files folder names, open to all resources inside the external configuration setting, the request can be directly 
2 setting in STATIC_URL = '/ static /' settings, provided that the external path prefix the html file set request packet of a third party, and regardless of the name of the file folder 1 
3 setting the STATICFILES_DIRS = [os.path.join (bASE_DIR, ' static'], "static" indicates you static files file folder 
4 STATICFILES_DIRS can put multiple static folder

"" "

 Routing Control  

In django of urls.py file

from django.contrib Import ADMIN
 from django.conf.urls Import URL
 from app01.views * # Import function introduced Application view 

the urlpatterns = [ 
    URL ( ' ADMIN / ' , admin.site.urls), comes # Django admin the 
    url ( ' the Test / ' , get_test), # own to write 
]

note:

  1 urlpatterns is a list of a plurality of values ​​can be put

  2 url is a function of the first parameter is a regular expression, is a view of the second parameter mapping function in views.py

  3 plead browser url path to the final did not add "/", it will redirect to "/" in the url again made the request, so the request can not add "/"


View function

Written application views.py file

三板斧:render,HttpResponse,redirect

from django.shortcuts import render, HttpResponse, redirect


def get_test(requests):
if requests.method == "GET":
print(requests.GET)
name = requests.GET.get("name")
name1 = requests.GET.getlist("name")
print(name, name1)
return HttpResponse("GET")
elif requests.method == "POST":
name2 = requests.GET.get("name")
name3 = requests.GET.getlist("name")
print(name2, name3)
return HttpResponse("POST")
return HttpResponse("错误请求")
"" " 
. 1 requests.method # request method for obtaining the front end request, GET, or the POST
2 requests.GET get request may acquire the data of the distal end <QueryDict: { 'name': [ 'Lynn', 'Egon']}>
. 3 can by dictionary value method, to obtain data requests.GET. the default value is the last value list
4 If you want to get all of the value list, with requests.GEt.getlist ( "name") method, will get a list of
5 POST request and get the same
"" "

 note:

When the post data submitted, the browser will throw an exception:

 
The first comment out setting:

 

database

 Based pymysql

views.py

 
 
from django.shortcuts import render, HttpResponse, redirect
import pymysql


def get_user_info(requests):
if requests.method == "GET":
return render(requests, "login.html")
elif requests.method == "POST":
conn = pymysql.connect(
host="132.232.98.201",
port=3306,
database="django_table",
user="root",
password="boonray",
charset="utf8",
autocommit=True
)# 连接数据库
name = requests.POST.get("name")
password = requests.POST.get("password")
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute ( "select * from django_user where name =% s and password =% s", (name, password)) # sql statement execution
user_info = cursor.fetchall () # obtain execution results
if user_info: Verify whether data exists #
return HttpResponse ( "Login successful")
return HttpResponse ( "Bad request")

 

Based orm

django database connection

setting in the configuration

DATABASES = {
    # 'Default': { 
# 'ENGINE': 'django.db.backends.sqlite3', # default is a small database of the sqlite3
# 'NAME': the os.path.join (base_dir, 'db.sqlite3'),
} #
"default": {
'ENGINE': 'django.db.backends.mysql',
'NAME': "django_table",
"the USER": 'the root',
"PASSWORD": '123',
"the HOST": " 127.0.0.1 ",
" PORT ": 3306,

}
}
# Note: the dictionary key is all uppercase

__Init__ configuration file in the project or application files in the package

pymysql Import 
pymysql.install_as_MySQLdb () # mysql_db replaced with a connection to the database pymysql

snake

Object-relational mapping, additions and deletions to achieve a simple data search table data change

  Class 1 mapping database tables

  2 is mapped to the attribute fields in the database

  3 to an object map data in the database

models.py file

increase

models.py file

 from django.db import models


Models here Wallpaper the Create your #.
# User table
class DjangoUser (models.Model):
ID = models.IntegerField (primary_key = True)
name = models.CharField (MAX_LENGTH = 32)
password = models.CharField (MAX_LENGTH = 32)

class Meta -:
= named db_table, "django_user"
  DEF __str __ (Self): # print target, the printing result of the name field value
    return self.name

 views.py

from django.shortcuts Import the render, the HttpResponse, the redirect
 from app01.models Import * DEF get_user_info (Requests):
     IF requests.method == " the POST " : 
        name = requests.POST.get ( " name " ) 
        password = requests.POST. GET ( " name " ) 
        USER_OBJ = DjangoUser.objects.create (name = name, password = password) # save data to the database, the newly created data object will return
         # the User = DjangoUser (name = name, password = password) # The second way to save #



        user.save () # call the save method, saved to the database, there is no return value 
        IF USER_OBJ:
             return HttpResponse ( " Registration Success " )
         the else :
             return HttpResponse ( " registration failed " )
     return the render (Requests, " login.html " )

delete

views.py

DELETE_USER DEF (Requests): 
delete_id = requests.GET.get ( "delete_id")
DjangoUser.objects.filter (ID = delete_id) .Delete () # fixed usage table .objects .... filter () corresponds to sql where, screened
return HttpResponse ( "deleted successfully")

 check

 views.py

def get_user (requests): 
All data # user_list = DjangoUser.objects.all () # query a database table, return QuerySet objects that can be indexed value
# user_list = DjangoUser.objects.filter () # filter added filter criteria , returns the QuerySet objects
# print (user.query) # object can perform query method, the object is to get the result of sql statement
    user = DjangoUser.objects.filter (). first ( ) # The result is a data object 
return render (requests, "login.html" , locals ()) # The third parameter must be a dictionary, locals are able to get all the variables of the current generate a dictionary

change

 views.py

def update_user(requests):
    update_id = requests.POST.get("update_id")
    name = requests.POST.get("name")
    password = requests.POST.get("password")
    user_id = DjangoUser.objects.filter(id=update_id).update(name=name, password=password)
    if user_id: # 返回结果是修改数据的id
        return HttpResponse("修改成功")

 

  


 

Guess you like

Origin www.cnblogs.com/tianzhh/p/11596198.html