Django study notes the second day

A review of the content of the previous section:
	1. Django request life cycle
		-> URL correspondence (matching) -> view function -> return user string
		-> URL correspondence (matching) -> View function -> Open an HTML file and read the content
		
	2. Create django projcet

		django-admin startproject mysite
		

		..
		
		mysite
			mysite
				- Profile
				- url.py
				- settings.py
			
		cd mysite
		python manage.py startapp cmdb
		
		mysite
			mysite
				- Profile
				- url.py
				- settings.py
			cmdb
				- views.py
				- admin.py
				- models.py # create database table

	3. Configuration
		
		template path
		static file path
		# CSRF
		
	4. Write the program

		a. url.py
			
			/index/    ->   func
			
		b. views.py
			
			def func(request):
				# contains all request data
				...
				return HttpResponse('string')
				return render(request, 'index.html', {''})
				retrun redirect('URL')
				
		c. Template language
			return render(request, 'index.html', {'li': [11,22,33]})
			
			{% for item in li %}
				<h1>{{item}}</h1>
			{% endfor %}
			
			
			********** Dots for indexing **********
			<h2> {{item.0 }} </h2>

1. Routing system, URL
	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<nid>\d+)-(?P<uid>\d+).html', views.detail)
	   
	   PS:
			def detail(request, *args,**kwargs):
				pass
	
	   Actual combat:
			a.
				url(r'^detail-(\d+)-(\d+).html', views.detail),
				
				def func(request, nid, uid):
					
					pass
			
				def func(request, *args):
					args = (2,9)
					
					
				def func(request, *args, **kwargs):
					args = (2,9)
	   
			b.
				url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)
				
				def func(request, nid, uid):
					pass
					
				def funct(request, **kwargs):
					kwargs = {'not': 1, 'uid': 3}
					
				def func(request, *args, **kwargs):
					args = (2,9)
	4、 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<pid>\d+)/(?P<nid>\d+)/', views.index, name='i3'),
		
		
		#Reverse the generated url
		def func(request, *args, **kwargs):
			from django.urls import reverse
			
			url1 = reverse('i1')                              # asdfasdfasdf/
			url2 = reverse('i2', args=(1,2,))                 # yug/1/2/
			url3 = reverse('i3', kwargs={'pid': 1, "nid": 9}) # buy/1/9/
		
		
		xxx.html
			
			{% url "i1" %}               # asdfasdfasdf/
			{% url "i2" 1 2 %}           # yug/1/2/
			{% url "i3" pid=1 nid=9 %}   # buy/1/9/
		
		Note:
			# current URL
			request.path_info
	5. 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),
			]
	
	6. Default value (owing)
	
	7. Namespaces (owe)
	
	
2. View
	1. Get user request data
		request.GET
		request.POST
		request.FILES
		PS:
			GET: get data				
			POST: submit data
			
	2. Multi-selected content such as checkboxes
		request.POST.getlist()
	3. Upload files
		# Upload files, make special settings for the form tag
		obj = request.FILES.get ('delete')
		obj.name
		f = 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
		
		====》
		
		Recommendation: use both
		
	5. Decorator
		owe

	
3. Template
	
	

Fourth, ORM operation
	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)
	
	create class
	
	a. Write the class first
		from django.db import models

		# app01_userinfo
		class UserInfo(models.Model):
			# id column, auto increment, primary key
			# Username column, string type, specified length
			username = models.CharField(max_length=32)
			password = models.CharField(max_length=64)
		
	b. Importing the module in the views is effective, so you need to register the APP

		INSTALLED_APPS = [
			'django.contrib.admin',
			'django.contrib.auth',
			'django.contrib.contenttypes',
			'django.contrib.sessions',
			'django.contrib.messages',
			'django.contrib.staticfiles',
			'app01',
		]
	Then after writing the data class in the models of the app, you need to run the following command to create the table
	c. Execute the command
		python manage.py makemigrations
		python manage.py  migrate
		
	d. ********** NOTE***********
		Django uses the MySQLdb module to link MySQL by default
		Actively modify it to pymysql, and add the following code to the __init__ file in the project folder with the same name:
			import pymysql
			pymysql.install_as_MySQLdb()
	
	1. Automatically create database tables based on classes
		# models.py under app
	
		python manage.py makemigrations
		python manage.py  migrate
		
		
		Field:
			String type
			
			
			number
			
			
			time
			
			
			binary
			
			自增models.AutoField(primary_key=True)
			
		Field parameters:
			null -> can db be nullable
			default -> default value
			primary_key -> primary key
			db_column -> column name
			db_index -> index
			unique -> unique index
			unique_for_date    ->
			unique_for_month
			unique_for_year
			auto_now -> when created, the time is automatically generated
			auto_now_add -> When updating, automatically update to the current time
			
				# obj = UserGroup.objects.filter(id=1).update(caption='CEO')
				# obj = UserGroup.objects.filter(id=1).first()
				# obj.caption = "CEO"
				# obj.save()
				
			choices -> Display a drop-down box in django admin to avoid connecting table queries
			     user_choices = (
				 (1, superuser),
				 (2, ordinary users),
				 (3, low-level users),
				 )
			    user_type_id = models.IntegerField(choices = user_choices,default= 1)
			blank -> can django admin be blank
			verbose_name -> django admin display field Chinese
			editable -> whether django admin can be edited
			error_messages -> error messages due
			help_text -> django admin prompt
			validators -> django form , custom error message (owes)
			
			
			Create a Django superuser: python manage.py createsuperuser
			
			
			
			
	2. Perform various operations on the data in the database table according to the class
	
		One-to-many:
		
			a. External inspection
			b.
				foreign key field _id
			c.
				models.tb.object.create(name='root', user_group_id=1)
				
			d.
				
				userlist = models.tb.object.all()
				for row in userlist:
					row.id
					row.user_group_id
					row.user_group.caption
					
					
	==================== Assignment: User Management ======================
	1. Add, delete, modify and check user groups
	2. Users add or delete the query
		- add must be dialog
		- delete must be a dialog
		- Modified, must show default value
		
	3. Better looking pages
	
	4. Preview:
		http://www.cnblogs.com/wupeiqi/articles/5246483.html
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325140906&siteId=291194637