Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Day_19-Django (2)

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Summary of this section:

1. Routing system URL

II. View

Third, template

IV. ORM operation

Problem 1:Django request Lifecycle

-> URL correspondence (match)-> View function-> return user string

-> URL correspondence (match)-> View function-> Open a HTML file and read the contents

Question 2: create a Django project

Django-admin startproject xxx

Cd xxx

Python manage.py startapp CMDB

All the steps to create a project

1. Create Django project django-admin startproject project name 2. Create APP cd project name python manage.py startapp cmdb 3, static file project.settings.py STATICFILES_DIRS = (os.path.join (BASE_DIR, "static"),) 4, template path DIRS = > [os.path.join (BASE_DIR,'templates') ] 5. Middlerware # comment csrf 6 in settings, url.py "login"-- > function name 7, Define views.pydef func (request) under the view function app: # request.method GET / POST # http://127.0.0.1:8009/home?nid=123&name=alex # request.GET.get ('' None) # get the data from the request # request.POST.get ('', None) # return HttpResponse ("string") # return render (request "path to HTML template") # return redirect ('/ only URL') 8. Template rendering special template language-- {{variable name}} def func (request): return render (request, "index.html", {'current_user': "alex"}) index.html. `User` current_ User` = > the last generated string.. Alex-- For loop def func (request): return render (request, "index.html", {'current_user': "alex",' user_list': ['alex','eric']}) index.html.. `current_ user` {% for row in user_list%} {% if row = = "alex"%} {{row}} {% endif%} {% endfor%} # Index # def func (request): return render (request) "index.html", {'current_user': "alex",' user_list': ['alex','eric'],' user_dict': {'K1FY:' V1mm, 'K2FY:' V2}}) index.html. `current_ user` {{user_list.1}} {{user_dict.k1}} {{user_dict.k2}} # conditional def func (request): return render (request, "index.html", {'current_user': "alex" "age": 18, 'user_list': [' alex','eric'], 'user_dict': {' K1BY: 'V1mm,' K2Qing: 'V2}}) index.html. `current_ user` {{user_list.1}} {{user_dict.k1}} {{user_dict.k2}} {% if age%} there are older men with age {% if age > 16%} {% else%} fresh meat {% endif%} {% else%} No age {% endif%}

&

&

1. Routing system URL

1. Three ways

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\ d +)-(? P\ d +) .html', views.detail)

Ps:

Def detail (request, * args,**kwargs):

Pass

Actual combat:

1.url (r'^ detail- (\ d +)-(\ d +) .html', views.detail)

Def func (request, nid, uid): pass def func (request, * args): args = (2) def func (request, * args, * * kwargs): args = (2)

2.url (r'^ detail- (? P\ d +)-(? P\ d +) .html', views.detail)

Def func (request, nid, uid): pass def funct (request, * * kwargs): kwargs = {'nid': 1,' uid': 3} def func (request, * args, * * kwargs): args = (2)

Name

Name the URL routing relationship, * you can generate the URL you want based on this name in the future *

Url (r'^ asdfasdfasdf/', views.index, name='i1'), url (r'^ yug/ (\ d +) / (\ d +) /', views.index, name='i2'), url (r'^ buy/ (? P\ d +) / (? P\ d +) /', views.index, name='i3'), def func (request, * args) * * kwargs): from django.urls import reverse url1 = reverse ('i1') # asdfasdfasdf/ url2 = reverse (' i2records, args= (1meme 2,)) # yug/1/2/ url3 = reverse ('i3levels, kwargs= {' pid': 1) "nid": 9}) # buy/1/9/ xxx.html {% url "i1"%} # asdfasdfasdf/ {% url "i2" 12%} # yug/1/2/ {% url "i3" pid=1 nid=9%} # buy/1/9/

Note:

# current URL

Request.path_info

Multi-level routing

Project/urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [url (r'^ cmdb/', include ("app01.urls")), url (r'^ monitor/', include ("app02.urls")),] app01/urls.py from django.conf.urls import url,include from django.contrib import admin from app01 import views urlpatterns = [url (r'^ login/', views.login)) ] app02/urls.py from django.conf.urls import url,include from django.contrib import admin from app02 import views urlpatterns = [url (r'^ login/', views.login),]

Default value

Namespace

A. Project.urls.py

From django.conf.urls import url,include urlpatterns = [url (r'^ an app01.urls', namespace='publisher-polls'), include ('app01.urls', namespace='author-polls')), url (r' ^ b)),]

B. App01.urls.py

From django.conf.urls import urlfrom app01 import views app_name = 'app01'urlpatterns = [url (r' ^ (? P\ d +) / $', views.detail, name='detail')]

C. App01.views.py

Def detail (request, competition): print (request.resolver_match) return HttpResponse (competition)

After defining url with namespace above, when using name to generate URL, it should be as follows:

V = reverse ('app01:detail', kwargs= {' pk':11})

{% url 'app01:detail' pk=12 pp=99%}

The routing system in django is different from the framework of other languages. In django, each requested url must have a route map so that the request can be handed over to a function in a view to be processed. Most other Web frameworks do a route map for a class of url requests, so that the routing system becomes concise.

Through the reflection mechanism, develop a dynamic routing system for django Demo: click to download

II. View

1. Obtain user request data

Request.GETrequest.POSTrequest.FILES

PS:

GET: getting data

POST: submitting data

2, checkbox and other selected content

Request.POST.getlist ()

3. Upload files

# upload files with special settings for the form tag

Obj = request.FILES.get ('fafafa') obj.namef = open (obj.name, mode='wb') for item in obj.chunks (): f.write (item) f.close ()

4. FBV & CBV

Function base view

Url.py

Index-> function name

View.py

Def function (request):

...

= "

/ index/-> function name

/ index/-> class

= "

Suggestion: use both

5. Decorator

Owe

III. ORM

Corresponding examples of 1.mysql and ORM

Select * from tb where id > 1 # correspondence models.tb.objects.filter (id__gt=1) models.tb.objects.filter (id=1) models.tb.objects.filter (id__lt=1)

1. Automatically create database tables based on classes

Create a class

a. Write the class first

Locate models.py:

From django.db import models

Class UserInfo (models.Model): # id column, self-increment, primary key # username column, string type, specified length username = models.CharField (max_length=32) password = models.CharField (max_length=64)

Find and add the last line as follows:

INSTALLED_APPS = ['django.contrib.admin',' django.contrib.auth', 'django.contrib.contenttypes',' django.contrib.sessions', 'django.contrib.messages',' django.contrib.staticfiles', 'app01',]

Execute a command

Python manage.py makemigrations python manage.py migrate

You have now created a table: app01_userinfo

Tip: if you are not using the default database, then you need to find setting.py 's DATABASE to change its contents.

DATABASES = {'default': {' ENGINE': 'django.db.backends.mysql',' NAME':'dbname', 'USER':' root', 'PASSWORD':' xxx', 'HOST':', 'PORT':',}}

# because Django uses a MySQLdb module when connecting to MySQL internally, but there is no such module in python3, it is necessary to use pymysql instead

Django uses the MySQLdb module to link MySQL by default

Actively modify it to pymysql, and add the following code to the _ _ init__ file under the folder with the same name as project:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report