ORM supplementary Basic operations (advanced data row operations)


The sorting

User_list = models. The UserInfo. Objects. All () order_by (' - id ', 'name') # - id represents descending, id on behalf of the ascendingCopy the code

grouping

from django.db.models import Count,Sum,Max,Min v =models.UserInfo.objects.values('ut_id').annotate(xxxx=Count('id')) # Equivalent to SELECT 'app01_userinfo'. 'ut_id', COUNT(`app01_userinfo`.`id`) AS `xxxx` FROM `app01_userinfo` GROUP BY `app01_userinfo`.`ut_id` ORDER BY NULLCopy the code
# with having packet filter v = models. The UserInfo. Objects. The values (' ut_id). Annotate (XXXX = Count (" id ")). The filter (xxxx__gt = 2) # equivalent to SELECT `app01_userinfo`.`ut_id`, COUNT(`app01_userinfo`.`id`) AS `xxxx` FROM `app01_userinfo` GROUP BY `app01_userinfo`.`ut_id` HAVING COUNT(`app01_userinfo`.`id`) > 2 ORDER BY NULLCopy the code
V = models. The UserInfo. Objects. The filter (id__gt = 2) values (' ut_id). Annotate (XXXX = Count (" id ")). The filter (xxxx__gt = 2) # equivalent to SELECT `app01_userinfo`.`ut_id`, COUNT(`app01_userinfo`.`id`) AS `xxxx` FROM `app01_userinfo` WHERE `app01_userinfo`.`id` > 2 GROUP BY `app01_userinfo`.`ut_id` HAVING COUNT(`app01_userinfo`.`id`) > 2 ORDER BY NULLCopy the code
Values (aliases =Count(column ID /1)) # annotate depends on valuesCopy the code

filter

Models. The UserInfo. Objects. The filter (id__gt = 1) # id > 1... (id__lt=1) # id<1...... (id__lte = 1) # id < = 1... (id__gte = 1) # id > = 1... (id__in=[1,2,3]) #id in [1,2,3]... (name__startswith = 'XXXX') #... (name__contains = 'XXXX') #... exclude(id=1) # not in (id=1)Copy the code

F, Q, extra method

  • F
From the django. Db. Models import F models. The UserInfo. Objects. All (). The update (age = F (" age ") + 1) # F () is used to take a particular column value in the objectCopy the code
  • Q(Construct complex query conditions)
# object mode (not recommended) from the django. The models import Q models. The UserInfo. Objects. The filter (Q (id__gt = 1)) models.UserInfo.objects.filter(Q(id=8) | Q(id=2)) # or models.UserInfo.objects.filter(Q(id=8) & Q(id=2)) # andCopy the code
  • Methods way
from django.db.models import Q q1 = Q() q1.connector = 'OR' q1.children.append(('id__gt', 1)) q1.children.append(('id', Q2.children. Append (('c1', 1)) q2.children. Append (('c1', 2)) q2.children. Append (('c1', 1)) q2.children. Append (('id', 1)) q3.children.append(('id', 1)) q3.children.append(('id', 2)) q3.children. 2)) q1. Add (Q3,'OR') # add(Q3,'OR') Add (q1, 'AND') con.add(q2, 'AND') con.add(q2, 'AND')Copy the code
  • Method practical application (multi-condition combination query)
Condition_dict = {" k ":[1,2,3,4],} con = Q() for k,v in condition_dict.items(): q = Q() q.connector = 'OR' for i in v: q.children.append(('id', i)) con.add(q,'AND') models.UserInfo.objects.filter(con) *********************************************************************** q1 = Q() q1.connector = 'OR' q1.children.append(('id', 1)) q1.children.append(('id', 10)) q1.children.append(('id', 9)) q2 = Q() q2.connector = 'OR' q2.children.append(('c1', 1)) q2.children.append(('c1', 10)) q2.children.append(('c1', 9)) q3 = Q() q3.connector = 'AND' q3.children.append(('id', 1)) q3.children.append(('id', 2)) q1.add(q3,'OR') con = Q() con.add(q1, 'AND') con.add(q2, Or (id=1 or id= 10 or id=9 or (id=1 AND id=2)) AND (c1=1 or c1=10 or c1=9)Copy the code
  • Extra (Add additional custom SQL statements)
models.UserInfo.objects.extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None) a. Select select_params=None from select_params; Where params=None, select * from table where c. Tables select * from table where c. Order_by =None SELECT * from table order by hereCopy the code
v = models.UserInfo.objects.all().extra( select={ 'n':"select count(1) from app01_usertype where id=%s or id=%s", 'm':"select count(1) from app01_userType WHERE id=%s or id=%s",}, select_params=[1,2,3,4]) for obj in v: Print (obj) name, obj id, obj. N) -- -- -- -- -- -- -- -- -- -- is equivalent to the query results as a field shows the column:  select # id, # name, # (select count(1) from tb) as n # from xb where ....Copy the code
models.UserInfo.objects.extra( select={'newid':'select count(1) from app01_usertype where id>%s'}, select_params=[1,], Where = [' age > % s'], params = [18,], order_by = [' - age], tables = [' app01_usertype ']) -- -- -- -- -- -- -- -- -- -- equivalent to the native SQL statements are as follows:  select app01_userinfo.id, (select count(1) from app01_usertype where id>1) as newid from app01_userinfo,app01_usertype where app01_userinfo.age > 18 order by app01_userinfo.age descCopy the code
result = models.UserInfo.objects.filter(id__gt=1).extra( where=['app01_userinfo.id < %s'], params=[100,], tables=['app01_usertype'], order_by=['-app01_userinfo.id'], The select = {' uid: 1, 'sw' : "select count (1) the from app01_userinfo"} # add query field) -- -- -- -- -- -- -- -- -- -- the select (1) AS "uid", (select count(1) from app01_userinfo) AS "sw", "app01_userinfo"."id", "app01_userinfo"."name", "app01_userinfo"."age", "app01_userinfo"."ut_id" FROM "app01_userinfo" , "app01_usertype" WHERE ("app01_userinfo"."id" > 1 AND (app01_userinfo.id < 100)) ORDER BY ("app01_userinfo".id) DESCCopy the code
  • Takes a specific field value
V = models. The UserInfo. Objects. All () only (' id ', 'name') # for field outside of the field will be the second SQL requestsCopy the code
  • Take all values except the current field
 v = models.UserInfo.objects.all().defer('name')
Copy the code
  • reverse
V = models. The UserInfo. Objects. All () order_by (' - id ', 'name'). The reverse () # only in order_by () method is effectCopy the code
  • Using the database Engine
models.UserInfo.objects.all().using('db2')

Copy the code
  • The aggregation
# statistics from total django. Db. Models import Count result = models. The UserInfo. Objects. The aggregate (k = Count (' ut_id, distinct = True), N =Count('id') # print(ruselt.query())Copy the code
  • Add data in dictionary format
obj = models.UserType.objects.create(**{'title': 'xxx'})
Copy the code
  • Add data with keyword arguments
obj = models.UserType.objects.create(title='xxx')
Copy the code
  • Batch Adding data
Objs = [models. The UserInfo (name = 'r11'),] models. The UserInfo. Objects. Bulk_create (objs, 10) # 10 for a submit data, 10 times suggest no more than 999Copy the code
  • Create/get
Obj, created = models. The UserInfo. Objects. Get_or_create (# if there is data acquisition, or directly to create the username = 'root1', PWD = 'ff', defaults = {' email: '1111111','u_id': 2, 't_id': 2})Copy the code
  • The condition
Models. The UserInfo. Objects. In_bulk ([1, 2, 3]) # according to the primary key Equivalent models. The UserInfo. Objects. The filter (id__in = [1, 2, 3])Copy the code
  • Raw (Writing native SQL statements)
name_map = {'title': 'name'} # converts the following title name v1 = models. The UserInfo. Objects. Raw (' SELECT id, title FROM app01_usertype ', translations = name_map)  for i in v1: print(i,type(i))Copy the code
  • Select_related: query active connect table, obtain all connected table data at one time (performance related: used when the amount of data is small)
Q = models. The UserInfo. Objects. All () select_related (# 'ut', 'gp) is equivalent to the select * from the UserInfo inner join usertype on... For row in q: print(row.name,row.ut.title) # Get data in the form of a linked tableCopy the code
  • Prefetch_related: not related to the table, but will perform multiple queries (performance related: used when the data is large and the query is frequent)
q = models.UserInfo.objects.all().prefetch_related('ut') # select * from userinfo; # select * from usertype where id in [2,4] for row in q: print(row.id,row.ut.title)Copy the code

XSS attack (cross-site scripting attack)


Simulated attacks: the premise need to set the corresponding annotation MIDDLEWARE = [# 'django. MIDDLEWARE. CSRF. CsrfViewMiddleware',]Copy the code

urls

url(r'^index/', views.index),
url(r'^comment/', views.comment),
Copy the code

views

def comment(request):
    if request.method == "GET":
        return render(request,'comment.html')
    else:
        v = request.POST.get('content')
        msg.append(v)
       return render(request,'comment.html')
def index(request):   
    return render(request,'index.html',{'msg':msg})
Copy the code

html

Comments < h1 > < / h1 > {% for item in MSG %} < div > {{item | safe}} < / div > # need to give response value add safe {% endfor %}Copy the code
Safe: def test(request) From django.utils.safestring import mark_safe temp = "<a href='http://www.baidu.com'> baidu </a>" newtemp = mark_safe(temp) Return render(request,'test.html',{'temp':newtemp})Copy the code
Hackers can forge websites and carry out XSS attacks to obtain cookies in the official website visited by users, so as to disguise the user's access to the official website for operation. Therefore, cookies are very important, and XSS must be enabled (XSS is enabled by default).Copy the code

CSRF(Cross-site request Masquerade Attack)


urls

R '^csrf1.html$', views.csrf1Copy the code

views


def csrf1(request):
    if request.method == 'GET':
        return render(request,'csrf1.html')
    else:
        return HttpResponse('ok')
Copy the code

html

<form method="POST" action="/csrf1.html"> {% csrf_token %} <input id="user" type="text" name="user" /> <input type=" value=" submit" /> <a onclick="submitForm(); </a> </form>Copy the code

Add: CSRF second processing: add decorators

From django.views import View from django.utils.decorators import method_decorator # CBV, Def wrapper(func): def inner(*args,**kwargs): return func(*args,**kwargs) return innerCopy the code
Class Foo(View): @method_decorator(wrapper) def get(self,request): pass def post(self,request): passCopy the code
Foo(View): def get(self,request): Foo(View): def get(self,request): pass def post(self,request): passCopy the code

CSRF (Ajax Request Pattern)

  • html
<form method="POST" action="/csrf1.html"> {% csrf_token %} <input id="user" type="text" name="user" /> <input Type ="submit" value=" submit" /> <a onclick="submit "; >Ajax submit </a> </form> <script SRC ="/static/jquery-1.12.4.js"></script>Copy the code
  • js
<script> function submitForm(){ var token = $.cookie('csrftoken'); Var user = $('#user').val(); $. Ajax ({url: '/csrf1.html', type: 'POST', headers:{' x-csrftoken ': token}, headers:{' x-csrftoken ': token}, headers:{' x-csrftoken ': token}, headers:{' x-csrftoken ': token}, # { "user":user}, success:function(arg){ console.log(arg); } }) } </script>Copy the code

views

def csrf1(request):
    if request.method == 'GET':
        return render(request,'csrf1.html')
    else:
        return HttpResponse('ok')
Copy the code

ORM functions related (using functions on HTML templates) simple_tag


Use built-in functions in templates

  • html
{{name | upper}} # upper said the built-in function, change your all letters to uppercaseCopy the code
  • views
def test(request):
return render(request,'test.html',{'name':'aaaaAA'})
Copy the code

Use custom functions in templates

  • Create the templateTags folder and create the xx.py module
From Django import template register = template.library () Def my_upper(value,arg): Def my_bool(value) def my_bool(value): Def my_lower(value,a1,a2,a3): return value + a1 + a2 + a3Copy the code
  • views
def test(request):
return render(request,'test.html',{'name':'aaaaAA'})
Copy the code
  • html
{xx % % load} {xx module # # import loading} < h2 > filter < / h2 > {{name | my_upper: "666"}} # most support two parameters {{name | upper}} {% if the name | my_bool %} < h3 > true < / h3 >} else {% % < h3 > false < / h3 > {% endif %} < h2 > tag < / h2 > {% my_lower "ALEX" "x" "SB" %} "V"Copy the code
  • Setting Registers the program block
INSTALLED_APPS = [...... 'app01',]Copy the code
  • Conclusion:
- simple_filter - up to two parameters, format: {{the first parameter | function name: "the second parameter"}} - can do condition judgment - simple_tag - unlimited: %} {% function parameters parametersCopy the code

Include the widget


html

The < div > < h3 > special beautiful components < / h3 > < div class = "title" > title: {{name}} < / div > < div class = "content" > content: {{name}} < / div > < / div >Copy the code
... {% include 'pub.html' %}...Copy the code

Cookies and Sessions (session is recommended)


Cookies are key-value pairs stored on the browser of the client, and Session is data stored on the server (key-value pairs in essence). Because cookies are used alone, they will retain the specific plaintext form of the user (sensitive information not converted into strings) and send it to the browser (insecure), so Session is recommended. Sessions send random strings that contain no user-sensitive information (security), where sessions rely on cookies,Copy the code

urls

Patterns = [... url(r'^login/', views.login), url(r'^index/', views.index),]Copy the code

views

def login(request): if request.method == 'GET': return render(request,'login.html') else: u = request.POST.get('user') p = request.POST.get('pwd') obj = models.UserAdmin.objects.filter(username=u,password=p).first() if obj: # 1. Generate random string # 2. Send to client # 3 via cookie. Server save # {random string # 1: {' username ':' alex ', 'email' : x ' '... } # } request.session['username'] = obj.username return redirect('/index/') else: Return render(request,'login.html',{' MSG ':' userid '}) def index(request): # Get the random string in the cookies of the client, check whether there is such string in the session, and check whether there is username in the value of the key corresponding to the session through the string. If v: return HttpResponse(' login succeeded :%s' %v) else: HttpResponse(' login succeeded :%s' %v) return redirect('/login/')Copy the code

setting

# SESSION_COOKIE_NAME = "sessionid" # sessionid Sessionid = random string # SESSION_COOKIE_PATH = "/" # SESSION_COOKIE_DOMAIN = None # Session cookie saved domain # SESSION_COOKIE_SECURE = False # SESSION_COOKIE_HTTPONLY = True # Whether Session cookies only support HTTP transfer # SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser to make the Session expire # SESSION_SAVE_EVERY_REQUEST = False (recommended True) The default after modification to save SESSION_ENGINE = 'django. Contrib. Sessions. Backends. Cashe' # engine, cache + database, SESSION__CASHE_ALLAS ='default' is recommendedCopy the code

User Login to Demo


models

from django.db import models
class Boy(models.Model):
    nickname = models.CharField(max_length=32)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=63)

class Girl(models.Model):
    nickname = models.CharField(max_length=32)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=63)

class B2G(models.Model):
    b = models.ForeignKey(to='Boy', to_field='id',on_delete='')
    g = models.ForeignKey(to='Girl', to_field='id',on_delete='')
Copy the code

urls

urlpatterns = [
    url('admin/', admin.site.urls),
    url(r'^login.html$', account.login),
    url(r'^index.html$', love.index),
    url(r'^loginout.html$',account.loginout),
    url(r'^others.html$',love.others),
]
Copy the code

Views (Create folder form to distinguish module relations)

  • The account module
from django.shortcuts import render,HttpResponse,redirect from app01 import models def login(request): Param request: :return: "" if request.method == 'GET': return render(request,'login.html') else: user = request.POST.get('username') pwd = request.POST.get('password') gender = request.POST.get('gender') rmb = Request.post.get (' RMB ') # if gender == "1": obj = models.Boy.objects.filter(username=user,password=pwd).first() else: obj = models.Girl.objects.filter(username=user,password=pwd).first() if not obj: Return render(request,'login.html',{' MSG ': 'username or password error '}) else: request.session['user_info'] = {'user_id':obj.id,'gender':gender,'username':user,'nickname':obj.nickname} return Redirect ('/index.html') def loginout(request: :return: """ if request.session.get('user_info'): Request.session.clear () # clear server database session (recommended) # request.session.delete(request.session.session_key) # Clear client session return  redirect('/login.html')Copy the code
  • Love module
from django.shortcuts import render,redirect,HttpResponse from app01 import models def index(request): Param request: :return: """ if not request.session.get('user_info'): Return redirect('/login.html') else: Gender = request.session.get('user_info'). Get ('gender') if gender == '1': user_list = models.Girl.objects.all() else: user_list = models.Boy.objects.all() return render(request,'index.html',{'user_list':user_list}) def others(request): Request: :return: param request: :return: """ current_user_id = request.session.get('user_info').get('user_id') gender = request.session.get('user_info').get('gender') if gender == '1': user_list = models.B2G.objects.filter(b_id=current_user_id).values('g__nickname') else: user_list = models.B2G.objects.filter(g_id=current_user_id).values('b__nickname') print('result', user_list) return render(request,'others.html',{'user_list':user_list})Copy the code

html

  • login.html
<form method="POST" action="/login.html"> {% csrF_token %} <p> User: <input type="text" name="username" /></p> <p> password: <input type="password" name="password" /></p> <p> Male <input type="radio" name="gender" value="1" /> female <input type="radio" name="gender" value="2" /> </p> <p> <input </p> <input type="submit" value=" submit" />{{MSG}} </form>Copy the code
  • Create HTML component user_header
</h1> <a href="/logout.html"> logout </a>Copy the code
  • index.html
{% include 'user_header.html' %} <h3> <a href="/others.html"> <li>{{ row.nickname }}</li> {% endfor %} </ul>Copy the code
  • others.html
{% include 'user_header. HTML '%} <h1> List of related members of the other sex </h1> <ul> {% for row in user_list %} {% if row.g__nickname %} <li>{{ row.g__nickname }}</li> {% else %} <li>{{ row.b__nickname }}</li> {% endif %} {% endfor %} </ul>Copy the code

The Form component


Getting to know the Form component

  • html
<form method="post" action="/login/">
    {% csrf_token %}
    <p>username:<input type="text" name="username">{{obj.errors.username.0 }}</p>
    <p>password:<input type="password" name="password">{{obj.errors.password.0  }}</p>
    <input type="submit" value="submit"> 
</form>
Copy the code
  • urls
Patterns = [... url(r'^login/$', views.login),]Copy the code

views

From django.forms import Form,fields # ------- Define the Form validation rule class LoginForm(Form): Cannot be empty,6-18 username = fields.CharField(max_length=18, min_length=6, required=True, error_messages={'required': 'user name cannot be empty', 'min_length' : 'it's too short' and 'max_length' : 'is too long,}) # regular validation: 16+ password = fields.CharField(min_length=16,required=True) def login(request): If request. Method == "GET": return render(request,'login.html') else: Obj = LoginForm(request.post) # if obj.is_valid(): Print (obj.cleaned_data) print(obj.cleaned_data) return redirect('http://www.baidu.com') else: Return render(request,'login. HTML ',{'obj':obj})Copy the code

Form validation process analysis

When LoginForm is instantiated, self.fields={'user': regular expression 'PWD ': regular expression}Copy the code
Flag = True errors cleaned_data for k,v in self.fields.items(): Input_value = request.post. get(k) # Loop to obtain the value of the k field (k must be consistent with the front-end field name) and check whether the value of the input_value matches the regular expression flag = False return flag -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- if obj. Is_valid () : # to return the result to True is verified print (obj. Cleaned_data) else: print(obj.errors) return render(request,'login.html')Copy the code

Form and Ajax submission validation (Ajax submission is not refreshed, last content is automatically retained)

  • html
< h1 > user login < / h1 > < form id = "f1" action = "/ login/" method =" POST "> {% csrf_token %} < p > < input type =" text "name =" user "/ > {{ obj.errors.user.0 }} </p> <p> <input type="password" name="pwd" />{{ obj.errors.pwd.0 }} </p> <input type="submit" /> <a onclick="submitForm();" > submit < / a > < / form > < script SRC = "/ static/jquery - 1.12.4. Js" > < / script > < script > function submitForm () {$(' c1 '), remove (); $.ajax({ url: '/ajax_login/', type: 'POST', data: $('#f1').serialize(),// serialize: user=alex&pwd=456&csrftoen= DFDF dataType:"JSON", success:function(arg){console.log(arg); If (arg. Status){}else{$.each(arg. MSG,function(index,value){#index Var tag = document.createElement('span'); var tag = document.createElement('span'); tag.innerHTML = value[0]; tag.className = 'c1'; $('#f1').find('input[name="'+ index +'"]').after(tag); }) } } }) } </script>Copy the code
  • urls
... url(r'^ajax_login/', views.ajax_login),Copy the code
  • views
class LoginForm(Form): Define the Form component class User = fields.charfield (required=True,min_length=6) PWD = fields.charfield (min_length=18) def ajax_login(request): import json ret={'status':True,'msg':None} obj = LoginForm(request.POST) if obj.is_valid(): print(obj.cleaned_data) else: ['status']=False [' MSG ']=obj. dumps(ret) print(obj. dumps) #print It automatically calls __str__(), which assembles the dictionary into a <ul> tag. Return HttpResponse(v)Copy the code

Common fields and parameters of the Form component

class TestForm(Form): t1 = fields.CharField( required=True, max_length=8, min_length=2, error_messages={ 'required': 'cannot be empty ', 'max_length':' too long ', 'min_length': 'too short ',}) t2 = fields.IntegerField(min_value=10, max_value=1000, error_messages={'required':' T2 cannot be null ', 'invalid': 'T2 format error, must be number ', 'min_value':' must be greater than 10', 'max_value': 'must be less than 1000',},) t3 = fields.emailfield (error_messages={'required': 't3 cannot be empty ', 'invalid': 't3 format error, must be mailbox format ',}) # is empty, length, format, Regular t4 = fields. URLField (t5) = fields. SlugField () t6 = fields. GenericIPAddressField t7 has () = fields. DateField () T8 = fields.datetimeField () t9= fields.regexfield ('139\d+') # Custom regular expression field validation rulesCopy the code
Generate HTML tags: Widget =widgets.Select, ******** to specify what HTML to generate, Select, Text,input/. Label =' username ', # obj.t1.label disabled=False, # suffix='-- >', Initial ='666'; help_text=' 666'; ', # Provide help informationCopy the code

The Form component retains the contents of the last input box

  • html
< Form action="/register/" method="POST" novalidate> #novalidate ignores the browser Form validation rule {% csrf_token %} <p> {{ obj.user }} {{ obj.errors.user.0 }} </p> <p> {{ obj.email }} {{ obj.errors.email.0 }} </p> <p> {{ obj.password }} {{ obj.errors.password.0 }} </p> <p> {{ obj.phone }} {{ obj.errors.phone.0 }} </p> <input type="submit" Value =" Submit "/>Copy the code
  • urls
url(r'^register/', views.register),
Copy the code
  • views
class RegiterForm(Form): user = fields.CharField(min_length=8) email = fields.EmailField() password = fields.CharField() phone = fields.RegexField('139\d+') def register(request): if request.method == 'GET': Obj = RegiterForm() return render(request,'register.html',{'obj':obj}) Obj = RegiterForm(request.post) # If obj.is_valid(): print(obj.cleaned_data) else: print(obj.errors) return render(request,'register.html',{'obj':obj})Copy the code

Form component to complete the student management system


models

from django.db import models class Classes(models.Model): Def title = models.CharField(max_length=32) def str__(self): Return self. Title class Student(models.Model): name = models.CharField(max_length=32) email = models.CharField(max_length=32) age = models.IntegerField(max_length=32) cls = models.ForeignKey('Classes',on_delete='') class Teacher(models.Model): Tname = models.charfield (max_length=32) c2t = models.manytomanyfield ('Classes'Copy the code

Class management

  • check
# urls


url(r'^class_list/',views.class_list),
Copy the code
# views

def class_list(request):
    cls_list = models.Classes.objects.all()
    return render(request,'class_list.html',{'cls_list':cls_list})
Copy the code
Class list # HTML < h1 > < / h1 > < div > < a href = "/ add_class/" > add < / a > < ul > {% for the row in cls_list %} < li > {{row. The title}} < a A href = "/ edit_class / {{row. Id}}" > edit < / a > < / li > {% endfor %} < / ul > < / div >Copy the code
  • increase
# urls

url(r'^add_class/',views.add_class),
Copy the code
# views class Form(Form): title = fields.RegexField(' full stack \d+') # def add_class(request): if request.method == 'GET': Return render(request,'add_class.html',{'obj':obj}) else: Obj = ClassForm(request.post) # if obj. Is_valid (): models.Classes.objects.create(**obj.cleaned_data) return redirect('/class_list/') return render(request, 'add_class.html', {'obj': obj})Copy the code
# HTML <h1> Add class </h1> <form method="post" action="/add_class/" novalidate> Obj.errors.title.0}} # 0 <input type="submit" value=" submit" >Copy the code
  • change
# urls url(r'edit_class/(\d+)',views.edit_class),# regex that accepts any numeric IDCopy the code
# views... Omit the Form component definition class... def edit_class(request, nid): if request.method == 'GET': Row = models. Classes. The objects. The filter (id = nid). The first (#) to page shows the initial value # obj = ClassForm (data = {" title ": Obj = ClassForm(initial={'title': Return render(request,'edit_class.html',{'nid':nid,'obj':obj}) else: obj = ClassForm(request.POST) if obj.is_valid(): # models.Classes.objects.filter(id=nid).update(title = obj.cleaned_data['title']) Models. The Classes. The objects. The filter (id = nid), update (* * obj. Cleaned_data) # dictionary format to insert data return redirect ('/class_list) return render(request,'edit_class.html',{'nid': nid,'obj':obj})Copy the code
Class # HTML < h1 > edit < / h1 > < form method = "POST" action = "/ edit_class / {{nid}} /" > {% csrf_token %} < p > {{obj. Title}} {{ Obj.errors.title.0}} </p> <input type='submit' value=" /> </form>Copy the code

Student management

  • check
# urls

url(r'^student_list/', views.student_list),
Copy the code
# views

def student_list(request):
    stu_list = models.Student.objects.all()
    return render(request, 'student_list.html', {'stu_list':stu_list})
Copy the code
# HTML < a href = "/ add_student/" > add < / a > < ul > {% for the row in stu_list %} < li > {{row. The name}} {{row. Email}} - {{row. The age }} {{row. Cls_id}} - {{row. CLS. Title}} < a href = "/ edit_student / {{row. Id}}" > edit < / a > < / li > {% endfor %} < / ul >Copy the code
  • increase
# urls

url(r'add_student/', views.add_student),
Copy the code
Class StudentForm(Form): name = fields.CharField( min_length=2, max_length=6, widget=widgets.TextInput(attrs={'class': Email = fields.EmailField(widget=widgets.TextInput(attrs={'class': 'form-control'})) age = fields.IntegerField(min_value=18,max_value=25,widget=widgets.TextInput(attrs={'class': 'form-control'})) cls_id = fields.IntegerField(# widget=widgets.Select(choices=[(1,' Shanghai '),(2,' Beijing ')]) widget=widgets.Select(choices=models.Classes.objects.values_list('id','title'),attrs={'class': 'form-control'}) # get radio dropdown cls_id=fields.ChoiceField( choices = models.Class.objests.values_list('id','title') widget = widgets.Select(attr={'class':''form-control}) ) ) def add_student(request): if request.method == 'GET': obj = StudentForm() return render(request,'add_student.html',{'obj':obj}) else: obj = StudentForm(request.POST) if obj.is_valid(): models.Student.objects.create(**obj.cleaned_data) return redirect('/student_list/') else: return render(request,'add_student.html',{'obj':obj})Copy the code
# HTML <form action="/add_student/" method="POST" novalidate> {% csrf_token %} <p> {{obj. Name}} {{obj. Errors. Name. 0}} < / p > < p > email: {{obj. Email}} {{obj. Errors. Email. 0}} < / p > < p > age: {{obj.age}}{{obj.errors. Age.0}} </p> <p> class: {{obj. Cls_id}} {{obj. Errors. Cls_id. 0}} < / p > < input type = "submit" value = "submit" / > < / form >Copy the code
  • change
# urls

url(r'^edit_student/(\d+)/', views.edit_student),
Copy the code
# views... Omit the Form component... def edit_student(request,nid): if request.method == 'GET': Row = models. Student. Objects. The filter (id = nid) values (' name ', 'email', 'age', 'cls_id'). The first (#) if you don't add first complains, Obj = StudentForm(initial=row) Return render(request,'edit_student.html',{'nid':nid, 'obj':obj}) else: obj = StudentForm(request.POST) if obj.is_valid(): models.Student.objects.filter(id=nid).update(**obj.cleaned_data) return redirect('/student_list/') else: return render(request,'/edit_student.html',{'nid':id, 'obj':obj})Copy the code
# HTML <link rel="stylesheet" href="/static/ bootstrap-3.5-dist/CSS /bootstrap. CSS "/> <div style="width: 500px; margin: 0 auto;" > <form class="form-horizontal" method="POST" action="/edit_student/{{ nid }}/"> {% csrf_token %} <div Class ="form-group"> <label class="col-sm-2 control-label"> </label> <div class="col-sm-10"> {{ obj.name }} </div> </div> <div class="form-group"> <label class="col-sm-2 Control - the label "> email: </label> <div class="col-sm-10"> {{ obj.email }} </div> </div> <div class="form-group"> <label class="col-sm-2 Control - the label "> age: </label> <div class="col-sm-10"> {{ obj.age }} </div> </div> <div class="form-group"> <label class="col-sm-2 Control - the label "> class: </label> <div class="col-sm-10"> {{ obj.cls_id }} </div> </div> <div class="form-group"> <div class="col-sm-offset-2 Col-sm-10 "> < form type="submit" class=" BTN btn-default" value=" submit"Copy the code

The teacher to manage

  • check
# urls

url(r'^teacher_list/', views.teacher_list),
Copy the code
# views

def teacher_list(request):
    tea_list = models.Teacher.objects.all()
    return render(request,'teacher_list.html',{'tea_list':tea_list})
Copy the code
Teacher # HTML < h1 > list < / h1 > < div > < a href = "/ add_teacher/" > add < / a > < / div > < table border =" 1 "> < thead > < tr > < th > ID < / th > < th > teacher name < / th > < th > teaching class < / th > < th > edit < / th > < / tr > < thead > < tbody > {% for the row in tea_list %} < tr > < td > {{row. Id}} < / td > < td > {{row. Tname}} < / td > < td > {{row. C2t}} < / td > < td > < a href = "/ edit_teacher / {{row. Id}} /" > edit < / a > < / td > < / tr > {% endfor %} </tbody> </table>Copy the code
  • increase
# urls

url(r'^add_teacher/', views.add_teacher),
Copy the code
TeacherForm(Form) TeacherForm(Form): Tname = fields. CharField (min_length = 2) cls_id = fields. MultipleChoiceField (# multiselect mode, filter out the dictionary is contained in the data list format {' cls_id ': ['2', '3']} instead of list string format {'cls_id': "[' 2 ', '3']"} # choices = models. Classes. The objects. The values_list (' id ', 'title'), # generate a drop-down box corresponding values, With the __init__() constructor, you can skip the choices keyword argument widget=widgets.SelectMultiple # Dropdown form component) # since the From component object does not restart to get the value of the database, Def __init__(self,*args,**kwargs) def __init__(self,*args,**kwargs): Super (TeacherForm,self).__init__(*args,**kwargs) # call the parent constructor Self. Fields [' cls_id] widget. Choices = models. Classes. The objects. The values_list (' id ', 'title') # to get the dictionary plug-in field choices # in the widget # obj = TeacherForm() # 1. # tname: fields.CharField(min_length=2) #} def add_teacher(request): if request == 'GET': obj = TeacherForm() return render(request,'add_teacher.html',{'obj':obj}) else: obj = TeacherForm(request.POST) if obj.is_valid(): Cls_id = obj. Cleaned_data. Pop (' cls_id ') # extract cls_id alone the value of the row = models. The Teacher. The objects. The create (* * obj. Cleaned_data) # ** dictionary, will automatically change the dictionary format {'tname': 'Tom '} converts to tname=' Tom' format data row.c2t.add(*cls_id) # * represents list format insert return redirect('/teacher_list/') return render(request,'add_teacher.html',{'obj':obj})Copy the code
# HTML <form method="POST" action="/add_teacher/" novalidate> {% csrf_token %} {{obj. Cls_id}} < / p > < input type = "submit" value = "submit" / > < / form >Copy the code
  • change
# urls

url(r'^edit_teacher/(\d+)/', views.edit_teacher),

Copy the code
# views def edit_teacher(request,nid): if request.method == "GET": Row = models. The Teacher. Objects. The filter (id = nid). The first () class_ids = row. C2t. Values_list (' id ') # associated class id value is [(3), (1)] # Zip () converts [(3,),(1,)] to [(3,) 1),] id_list = list(zip(*class_ids))[0] if list(zip(*class_ids)) else [] # obj = TeacherForm (initial = {' tname: row. Tname 'xx' : [1, 2, 3]}) obj = TeacherForm (initial = {' tname: row. Tname 'cls_id: id_list}) return render(request,'edit_teacher.html',{'obj':obj})Copy the code
# html

{{ obj.tname }}
{{ obj.cls_id }}
Copy the code

Form common component customization


class TestForm(Form): T1 = fields. MultipleChoiceField (# test boxes, value choices = [(1, "basketball"), (2, 'football')]. # # value widget set = widgets. CheckboxSelectMultiple generated boxes, component) t2 = fields. MultipleChoiceField (choices = [(1, "basketball"), (2, 'football')]. T3 = fields.filefield (widget= widgets.fileinput # FileInput box)Copy the code

Hooks in Form components (extending custom functions)


class TestForm(Form): User = fields.CharField(# add RegexValidator(r'^[0-9]+$'), RegexValidator(r'^[0-9]+$'), ),) email = fields.emailfield () def clean_user(self): # is often used to extend the existing in the user name is in the database, the verification code matches, the participation request v = self. Cleaned_data [' user '] if models. The Student. The object. The filter (name = v). The count () : Raise ValuedationError(' user already exists ') return self. Cleaned_data ['user'] def clean(self): User =self.cleaned_data.get('user') email=self.cleaned_data.get('email') if models.Stuent.objects.filter(user=user,email=email).count(): Raise ValuedationError(' User name and mailbox union already exist ') return self.cleaned_dataCopy the code

Ajax submits the data section


Native Ajax submits data

Function add2() {var XHR = new XMLHttpRequest(); Xhr.onreadystatechange =function () {if (xhr.readyState == 4){// Alert (xhr.responseText); } } xhr.open('GET','/add2/? i1=12&i2=19'); xhr.send(); } function add2() {var XHR =new XMLHttpRequest(); xhr.onreadystatechange=function () { if (xhr.readyState == 4){ alert(xhr.responseText); } } xhr.open('POST','/add2/'); xhr.setRequestHeader('Content-Type', 'Application /x-www-form-urlencoded ') # xhr.send('i1=12&i2=19'); }Copy the code

Pseudo Ajax submits data

<form id="f1" method="POST" action="/fake_ajax/" target="ifr"> <iframe id="ifr" name="ifr" style="display: none"></iframe> <input type="text" name="user" /> <a onclick="submitForm();" </a> </form> <script> function submitForm(){// attach the loadIframe to the memory. Document.getelementbyid (' ifR '). Onload = loadIframe; onload = loadIframe; document.getElementById('f1').submit(); } function loadIframe(){ var content = document.getElementById('ifr').contentWindow.document.body.innerText; // Get the data in the tag alert(content); } </script>Copy the code

Upload a file


Native Ajax upload files

  • html
<a onclick="upload1();" <a onclick="upload1();" </a> <div id="container1"></div> <script> function upload1(){var formData = new formData (); Formdata.append ('k1','v1'); formData.append('fafafa',document.getElementById('i1').files[0]); Var XHR = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ var file_path = xhr.responseText; var tag = document.createElement('img'); tag.src = "/"+ file_path; document.getElementById('container1').appendChild(tag); }}; xhr.open('POST','/upload/'); xhr.send(formData); } </script>Copy the code
  • views
import os def upload(request): if request.method == 'GET': return render(request, 'upload.html') else: File_obj = request.files.get ('fafafa') # File_obj.name) # install file path with open(file_path, 'wb') as f: for chunk in file_obj.chunks(): F.write (chunk) return HttpResponse(file_path)Copy the code
  • JQuery Ajax uploads files
  • html
<h1> <input type="file" id="i2" /> </div> <script SRC ="/static/jquery-1.12.4.js"></script> function upload2() {var formData =  new FormData(); formData.append('fafafa',$('#i2').files[0]); $. Ajax ({url:'/upload/', type:'POST', data:formData, contentType:false, # Ajax will add the request header processData:false by default, Function (arg) {var tag = document.createElement('img') tag.src='/'+arg; $('#container2').append(tag) } }) }Copy the code
  • views
Same as background processing with native AjaxCopy the code

Pseudo Ajax upload files (better browser compatibility)

  • html
<h1> Pseudo Ajax upload file </h1> <form ID ="f1" method="POST" action="/upload/" target="ifr" encType ="multipart/form-data"> <iframe id="ifr" style="display: none" name="ifr"></iframe> <input type="file" name="fafafa"/> <a onclick="upload3();" </div> function upload3() {document.getelementById ('ifr').onload = loadIframe; document.getElementById('f1').submit(); } function loadIframe() { var content = document.getElementById('ifr').contentWindow.document.body.innerText; var tag = document.createElement('img'); tag.src='/'+content; $('#container3').append(tag); }Copy the code
  • views
Same as background processing with native AjaxCopy the code

Jsonp (to solve cross-domain problems, requestor and responder agree on rules)


When using Ajax: access your domain URL- can access other domain URL- blocked (cross-site request) Blocked reason: Browser: Because of the same-origin policy, when Ajax sends a request across domains, the browser refuses to receive the response data. However, when a script tag sends a request, the returned data can be allowed to be received without being blocked by the browser.Copy the code
Example: <a onclick="sendMsg();" </a> <script SRC ="/static/jquery-1.12.4.js"></script> {# <script SRC ="/static/common2.js"></script> <script SRC ="/static/common2.js"></script> function sendMsg() { Var tag = document.createElement('script'); var tag = document.createElement('script'); . Immediately implement the function tag in js file. The SRC = 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403' Document. The head. The appendChild (tag)} # using the way of requirement: client: send the function name, URL? Function XXX (arg){} Funcname = request.get. When GET (callback) returns, pass the data to be returned as an argument to funcName (...). Note: To achieve cross-domain data interaction, both parties need to agree on the function rules in advanceCopy the code
Function f1() {alert(' KKK ')} # common2.js function list(arg){# common1.js console.log(arg)}Copy the code

Custom apis are used to return data

  • urls
url(r'^users/', views.users),
Copy the code
  • views
def users(request): Print (' request coming ') callback = request.get.GET (' funcName ') user_list=[' Leo ', 'Tom ',' Jack '] temp = '%s(%s)'%(callback, User_list) print(temp) # return HttpResponse(json.dumps(user_list)) return HttpResponse(temp) # Return a string objectCopy the code
  • Setting configuration ‘
ALLOWED_HOSTS = ['www.s4.com'] # Host allowed to accessCopy the code
  • Configuration on the LOCAL PC
C:\Windows\System32\drivers\etc Add 127.0.0.1 www.s4.com to the hosts fileCopy the code
  • Two solutions
<input type="button" onclick="sendMsg();" <input type="button" onclick="sendMsg2();" < static/jquery-3.3.1.min.js ></ static/jquery-3.3.1.min.js > Use the json form cross-site complete data interaction #} function sendMsg () {$. Ajax ({url: 'http://www.s4.com:8001/users/', type: 'GET', {# declare jSONp to send data, not XMLHttpResponse to send data, jSONP in GET form, even if declared in POST form will be automatically converted to GET #} dataType: Bbb#} JSONP: 'funcname', {# define the callback function #} jsonpCallback: Function sendMsg2() {var tag = document.createElement('script'); var tag = document.createElement('script'); {# to return the result is: the BBB ([' Leo ', 'Tom', 'jack']) #} tag. The SRC = "http://www.s4.com:8001/users/?funcname=bbb"; document.head.appendChild(tag); } function bbb(arg) { alert(arg); }Copy the code

CORS solves cross-domain problems (cross-source resource sharing) (add values to response headers)


A simple request

<input type="button" onclick="getUsers();" Value = "cors across source resource sharing way" > function getUsers () {$. Ajax ({url: 'http://www.s4.com:8001/new_users/', type: "GET", success:function (arg) { alert(arg) } }) }Copy the code

Third-party Server

 url(r'^new_users/', views.new_users),
Copy the code
def new_users(request): User_list = ['lleo', 'Tom ', 'jack'] obj = HttpResponse(json.dumps(user_list)) # Obj [" access-Control-allow-origin "]='http://www.s5.com:8000' # obj[" access-Control-allow-origin "]= "*" print(' request ') return objCopy the code

Complex request

  • Third-party Server
Def new_users(request): if request. Method == 'OPTIONS': obj = HttpResponse() obj["Access-Control-Allow-Origin"] ='*' obj["Access-Control-Allow-Origin"] ='DELETE' return obj obj  = HttpResponse('adsf') obj["Access-Control-Allow-Origin"] = '*' return objCopy the code