# # # directory:

  • Django Tutorial part 1 – Django views and urls
  • Django Tutorial ii – Django views with URL progression
  • Django Tutorial (3) – Django Forms
  • Django Tutorial (4) – Django templates and progression
  • Django models (databases) and common Django Query methods
  • Django Tutorial 5 – Upload and display
  • Django Tutorial part 1 – Build a simple blog system
  • Django Hands-on (Part 2) – Create a course selection system

# 1. # # # MVC

  • Most development languages have an MVC framework
  • The core idea of the MVC framework is decoupling
  • Reduce the coupling between the functional modules, facilitate the change, easier to reconstruct the code, achieve the maximum reuse of the code
  • M stands for Model, mainly used to encapsulate the database layer
  • V stands for View, which is used to show the results to the user
  • C stands for Controller and is the core for processing requests, retrieving data, and returning results

###MVT

  • Django is a Web development framework for Python
  • Different from MVC, it belongs to MVT framework
  • M stands for Model, responsible for interacting with the database
  • V stands for View and is the core responsible for receiving requests, obtaining data, and returning results
  • T stands for template, which is responsible for rendering content to the browser

Django is a free, open source Web framework developed in Python that can be used to quickly build high-performance, elegant websites!

Django official website Django official documentation Describes how to install Django

Django is a framework based on MVC constructs. But with Django, the controller accepts user input and the framework handles it itself, so Django focuses more on models, templates, and Views, called MTV patterns.

BSD: The BSD license was developed with the release of BSD UNIX by the University of California, Berkeley, with modified versions adopted by Apple and Apache. The BSD protocol is a member of the “permissive free software license” that imposes minimal restrictions on software reuse.

The BSD protocol allows authors to use resources under the protocol and incorporate them into a private version of software that can be distributed using the closed source software protocol.

#2. Environment building

  1. Download the Ubuntu image file at address one, address two, address three

  2. Install ubuntu

  3. Install PIP, using the appropriate code below

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python-pip
Copy the code

PIP installation packages are common to Python development users. But the download speed of foreign sources is too slow, waste of time, and a lot of software is always wall, so replace the PIP installation source with domestic mirror, can greatly improve the download speed, but also can solve the wall caused by the trouble of not installing the library, improve the success rate of installation. There are many sources available on the web. The one recommended here is Tsinghua University’s PIP source, which is a mirror image of pYPI and synchronizes every 5 minutes.

/.pip/pip.conf (if not, create one), press Ctrl + H to see hidden file, change index-url to tuna:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
Copy the code

4. Install Django with PIP (version 1.11 recommended)

(sudo) PIP install Django or (sudo) PIP install Django==1.8.16 or PIP install Django==1.11Copy the code

Check whether the installation is successful

>>> import django
>>> django.VERSION
(1, 11, 'final', 0)
>>> 
>>> django.get_version()
'1.11'
Copy the code

# 3. Installation of pycharm

  1. Download the JDK

  2. Decompress and enter the tar ZVXF jdK-8u131-linux-x64.tar. gz command

  3. To create a JVM file, enter sudo mkdir /usr/lib/jvm

  4. Sudo mv jdk1.8.0_131/ /usr/lib/ JVM / ** ** If there is no JVM file, executing this statement will automatically create a JVM file, but will only put the jdk1.8.0_25 and its files into the JVM file, which is different

  5. /. Bashrc is valid only for the current user. Sudo vim ~/.profile is valid only for the current user.

exportJAVA_HOME = / usr/lib/JVM/jdk1.8.0 _131export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export PATH=${JAVA_HOME}/bin:$PATH
Copy the code
  1. Make the modification take effect immediatelysource ~/.profile
  2. Verify the JDK input command:java -version

To enable you to drag and drop files from Windows to Ubuntu, install VMware Tools.

#5.Django’s main module

  • Urls. Py url entry, associated with a function (or generic class) in the views.py corresponding to a function that accesses the url.

  • Views.py handles user requests from urls.py, and by rendering templates pages you can export content, such as log-in user names and user-requested data, to a web page.

  • Models.py is associated with database operations, and is used when storing or reading data, but not when you don’t need a database.

  • The forms.py form, the submission of the user’s input to the browser, the validation of the data, and the generation of the input box. You don’t have to use it.

  • The templates function in the views.py folder renders the Html templates in templates to create a web page with dynamic content, although caching can be used to speed things up.

  • Admin.py backend, you can have a powerful backend with very little code.

  • Settings. py Django Settings, configuration files, such as DEBUG switches, static file locations, etc.

#6.Django basic commands

  • Create a New Django Project
Py startProject project_name Especially on Windows, if you get an error, try using Django-admin instead of django-admin.pyCopy the code

Note that project_name is your own project name and must be a valid Python package name, such as 1a or A-B.

  • To create an app, go to the project directory, CD project_name and run the following command (same below, CD project_name is not required if you are already in the project directory)
Python manage.py startApp app_name or django-admin.py startApp app_nameCopy the code

Generally, a project has multiple apps. Of course, a generic app can also be used in multiple projects. App name must be a valid Python package name, such as blog, news, aboutus, etc.

  • Create database tables or change database tables or fields
Django 1.7.1 and above use the following commands# 1. Create the changed file
python manage.py makemigrations
# 2. Apply the generated py file to the databasePython manage.py Migrate Python manage.py syncdb is used in older versions of Django 1.6 and belowCopy the code

This approach allows you to create tables that correspond to the models.py code in a database such as SQL, without manually executing the SQL yourself. Note: To make changes to existing Models, Django prior to 1.7 does not automatically change table structures, but there is a third-party utility called South

  • Use the development server. The development server is used during development. Generally, it automatically restarts after modifying the code, facilitating debugging and development.
python manage.py runserver
 
If a port is used, you can use another port:Python manage.py runServer 8001 Python manage.py runServer 9999killDrop processes that occupy ports.# monitor all available IP addresses on the machine.Python manage. Py runserver then executes 0.0.0.0:8000If you are on an extranet or LAN computer, you can view the development server on another computer
Access the corresponding IP plus port, such as http://172.16.20.2:8000
Copy the code
  • Clearing the database
python manage.py flush
Copy the code

This command asks for yes or no, and selecting yes clears out all data except for the empty table.

  • Creating a Super Administrator
python manage.py createsuperuser
 
The email can be left blank. The username and password are mandatory
 
Alter user password:
python manage.py changepassword username
Copy the code
  • Django project environment terminal
python manage.py shell
Copy the code

1. In Django, urls are written in a file called urls.py, using regular expressions that correspond to a function (or generic class) in views.py.

  1. Create a new project named Zebk
django-admin startproject zebk
Copy the code

Note: If django-admin does not work, use Django-admin.py 2. Create a new app named Zhong

python manage.py startapp zhong  # Zhong is the name of an app
Copy the code
  1. Note: Django 1.8.x and above also has a migrations folder. Django 1.9.x also comes with an apps.py file in addition to Django 1.8.

Our new definition to the Settings app. Py the INSTALL_APPS modify mysite/mysite/Settings. Py

INSTALLED_APPS = (
    'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'zhong'.)Copy the code

What it does: If a new app is not added to INSTALL_APPS, Django will not automatically find template files (files under app-name/templates/) and static files (files under app-name/static/) in your app.

Open the views.py file under /zebk and add the following content

# -*- coding: utf-8 -*- 
from django.http import HttpResponse
 
def index(request):
    return HttpResponse(u"Hellow in two disease control,!")
Copy the code
  1. The first line declares that the encoding isutf-8Because we use Chinese in the code, if not declare an error.
  2. The second line introduces HttpResponse, which is used to return content to a web page, just like in PythonprintSame thing, exceptHttpResponseIs to display content on a web page.
  3. We defined oneindex()Function, the first parameter must be request, which is related to the request from the web page. The request variable contains the content of get or POST, user browser, system and other information.
  4. The function returns oneHttpResponseObject, which can go through some processing and eventually display a few words on a web page.

###3. Define the URL associated with the view function

  1. Open the mysite/mysite/urls.py file and modify the code in it: From mysite/urls.py, import the module django.conf.urls.include and add it to the list of urlpatterns, so mysite/urls.py looks like this:
# mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^zhong/', include('zhong.urls')),
    url(r'^admin/', admin.site.urls),
]
Copy the code

2. Create urls.py in zhong as follows:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^ $', views.index, name='index'),]Copy the code

Then run Python manage.py runServer on the terminal and we should see something like the following:

 python manage.py runserver
 
Performing system checks...
 
System check identified no issues (0 silenced).
 
You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate'To apply them. December 22, 2015-11:57:33 Django Version 1.9, using Settings'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Copy the code

Open the web page and type127.0.0.1:8000 / zhong

#8. Administrative operations

  • The site is divided into “content publishing” and “public Access” sections
  • The “content publishing” section is responsible for adding, modifying, and removing content, and developing these repetitive features is tedious and uncreative work. To do this, Django completely automatically generates admin modules based on the defined model classes ### create an admin user using Django admin
Python manage.py createsuperuser, enter the user name, mailbox, and password as promptedCopy the code
  • Start the server, log in to the server through 127.0.0.1:8000/admin, and enter the user name and password
  • On the management site, you can manage groups and Users by default

### Manage interface localization

  • Edit settings.py to set the encoding and time zone
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
Copy the code

### Register the booktest model with admin

  • Open the booktest/admin.py file and register the model
from django.contrib import admin
from models import BookInfo
admin.site.register(BookInfo)
Copy the code
  • Refresh the management page to add, delete, change, and check BookInfo data

  • Problem: If Chinese is returned in STR methods, ASCII errors will be reported when modifying and adding

  • Encode (‘ utF-8 ‘) ### Custom admin page

  • Django provides the admin.modeladmin class

  • By defining subclasses of ModelAdmin, you can define how the model is displayed on the Admin interface

class QuestionAdmin(admin.ModelAdmin):
    ...
admin.site.register(Question, QuestionAdmin)
Copy the code

##### List page properties

  • List_display: Displays fields that can be sorted by clicking on the column header
list_display = ['pk'.'btitle'.'bpub_date']
Copy the code
  • List_filter: the list_filter field is displayed on the right
list_filter = ['btitle']
Copy the code
  • Search_fields: Search field. The search box appears on the top
search_fields = ['btitle']
Copy the code
  • List_per_page: pagination. The pagination box appears at the bottom
list_per_page = 10
Copy the code

##### Add and modify page properties

  • Fields: Indicates the sequence of attributes
fields = ['bpub_date'.'btitle']
Copy the code
  • Fieldsets: Attribute grouping
fieldsets = [
    ('basic', {'fields': ['btitle']}),
    ('more', {'fields': ['bpub_date']]}),Copy the code

##### Associated object

  • There are two ways to register the HeroInfo model class

    • Method 1: Same as the BookInfo model class
    • Method 2: Associate registration
  • HeroInfo is registered as BookInfor

  • Next, implement associated registration

from django.contrib import admin
from models import BookInfo,HeroInfo

class HeroInfoInline(admin.StackedInline):
    model = HeroInfo
    extra = 2

class BookInfoAdmin(admin.ModelAdmin):
    inlines = [HeroInfoInline]

admin.site.register(BookInfo, BookInfoAdmin)
Copy the code
  • You can change the inline mode to a table
class HeroInfoInline(admin.TabularInline)
Copy the code

##### Display of Boolean values

  • The display of published gender is not an intuitive result and can be encapsulated using methods
def gender(self):
    if self.hgender:
        return 'male'
    else:
        return 'woman'
gender.short_description = 'gender'Replace hgender class HeroInfoAdmin(admin.modelAdmin) with gender in the admin registry: list_display = ['id'.'hname'.'gender'.'hcontent']
Copy the code