Django models

First, Django follows the MVC pattern.

M:Model, Model, interact with the database

V:View HTML page

C:Controller, the Controller, receives requests, processes them, returns data, interacts with the view

The big idea in MVC is decoupling, doing their own thing.

Here are some ideas:

Such as a landing page (view), click on the account and password sent to the Controller (Controller) in the MVC framework, we processed from Controller, need to query the database, but not to operate the database directly, here we are going to operate the database through the Model, the back is the same.

In Django, Django changes the controller to Template, which is the same, but with a different name. It calls its mode MVT.

The difference is that V now has the same function as C in MVC and T has the same function as V in MVC.

Although it calls itself MVT, it essentially follows MVC.

Installing a Virtual Environment

Install a virtual environment similar to Python so that the modules used in this project are not relevant to other projects.

First you need to install the module:

pip3 install virtualenv

Install an extension package:

pip3 install virtualenvwrapper-win

So we’re going to create a virtual environment that’s all on drive C, and we’re going to change the path.

Add environment variables:

This computer -> Properties -> Advanced -> Environment Variables -> System variables click Add, variable name write WORKON_HOME, variable value write a path, (you create virtual environment want to place)

Create virtual environment command: mkvirtualenv name

If you have python3 and python2 installed, use -p to specify which version to use.

Exit the virtual environment: deactivate

Enter a virtual environment: Workon name

Check out the virtual environment workon you created

Delete a virtual environment: rmVirtualenv

After creating the virtual environment, the packages you install will be in the folders you set up. And the commands created are all the same.

Create a project

1. Create virtual environment:

Let’s create a virtual environment called djangoStudy: mkVirtualenv djangoStudy

2. Install the Django framework

PIP install Django ==1.8.2

View our virtual environment installed with the above module: PIP List.

Create a project

Before creating the project we create a folder to hold our project: md folder name

I’m going to create a directory for xuexi. When executing the secret order to create a folder, switch to the virtual swap folder.

After xuexi is created, let’s CD xuexi into this folder.

Create a project: Django-admin startProject Name of the project

I’m going to call my project test1.

4. Directory structure

Can be seen below xuexi:

test1

__init__ indicates that test1 is a Python package

Settings. py configuration file

Urls.py routing configuration

Wsgi. py (WSGI protocol) server and Django interface

Manage.py manages files

5. Create an app

First switch the directory to test1, CD test1.

Each module corresponds to an application. Run the python manage.py startapp command to create the application name

I’ll write student here

Go into your newly created app and you can see:

migrations   

__init__ indicates that migrations is a package

__init__ indicates that your application is a package

Admin.py is related to the backstage administration of the website

Models. Py model

Tests.py tests the code file

Views. py View function

6. Associate the application with the project

Need to modify the configuration file in order to modify pycharm to open.

6.1. Open the configuration file settings.py.

6.2. Go to INSTALLED_APPS and put our British name in it. I’ll say (with a comma) : ‘student’,

7. Run projects

Run the python manage.py runserver command in tese1

He’ll tell you to enter 127.0.0.1:8000/ in your browser to access it.

When our visit appears:

It means we’ve got the project up and running. \

ORM framework

That means object-relational mapping.

The ORM framework is built into Django. Using this framework makes it easier for us to operate the database.

Instead of writing simple Sql statements, create a class that maps the fields of a table in a database.

Use action classes to manipulate tables in a database. So in Models you write the same classes as tables and fields in the database.

It can also create tables in the database for you based on the classes you create.

Models

In models.py we write:

The class name is the name of the table

class stuinfo(models.Model):

# name CharField(max_length=20)

    stuname = models.CharField(max_length=20)

DateField Date type

    bri_date = models.DateField()

The id primary key doesn’t have to be written, it’s automatically generated

Other types:

BooleanField(default=False) # bool

ForeignKey(‘ table name ‘) # set ForeignKey(‘ table name ‘) # set ForeignKey(‘ table name ‘) # set ForeignKey(‘ table name ‘)

If I want him to generate a table:

Divided into two steps: Mr Migration file, using migration file regeneration table

1. Generate migration files

Run the python manage.py makemigrations command

This file will be placed in the Migrations directory

2, use migration files to regenerate tables

Run the python manage.py migrate command

It generates a database, not mysql, of course, but sqlite3 is used by default in Django if you don’t set what database to use. I won’t say more here.

\

Use Models to manipulate the table:

The import module

from student.models import stuinfo

Import the date module

from datetime import date 

# add data:

s = stuinfo()

S.tuname = ‘zhang SAN’

s.bri_date = dete(‘2000′,’1′,’1’)

s.save()

Select * from id where id = 1

s1 = student.objects.get(id = 1)

# select * from all

s2 = student.objects.all()

# display data

s1.stuname

s1.bri_date

# modified

s1.stuname = ‘123’

s1.save()

# remove

s1.delete()

Multi-table LianZha

Let’s add another class to Models:

class person(models.Model):

    # name

    name = models.CharField(max_length=20)

Outside the # key

    sid = models.ForeignKey(‘stuinfo’)

Multi-table join has a foreign key, we use the foreign key to query

Query the second table through the first table

s1 = student.objects.get(id = 1)

Select * from person where nid = 1; select * from person where nid = 1

s1.person_set.all()

Query the first table through the second table

p1 = person.objects.get(id = 1)

p1.student

P1.student. stuname # select stuname from stuname

Add a second table

s1 = student.objects.get(id = 1)

p2 = person()

P2.name = ‘flower’

A foreign key requires an object to be assigned

p2.sid = s1

Query foreign key values

Assignment is an object, so how do we find the id value?

p3 = person.objects.get(id = 1)

Select * from dictionary where id = ‘id’; select * from dictionary where id = ‘id’

p3.nid_id

Background Management (admin)

Django gives us a way to quickly generate admin pages behind the scenes.

1. Modify the page into Chinese

Modify the setting file and find LANGUAGE_CODE=’en-us’

LANGUAGE_CODE=’zh-hans’

2. Chinese time

Find TIME_ZONE = ‘UTC’ and change to

TIME_ZONE = ‘Asia/Shanghai’

3. Create an administrator account

Run python manage.py createsuperuser

You will be prompted for a user name, email address (optional), and password. Just set one up yourself

4. Run projects

Run the python manage.py runserver command

5. Log in to the administrator page

Type 127.0.0.1:8000/admin in your browser, and you’ll get the administrator page. Just log in.

Register model classes

Register the model classes in admin.py to help us generate the corresponding administrative pages.

Enter registration for our Stuinfo table.

In admin.py add:

from student.models import stuinfo

admin.site.register(stuinfo)

This completes the stuinfo table registration.

Next, refresh our browser’s admin page.

There will be one more team for stuinfo table management.

We can add data to the stuinfo table in.

After saving, it will display:

What if I want to display my name? \

The stuinfo object is actually the result of our STR (stuinfo) converting an object to a string,

So we just need to override the __str__ method in stuinfo in Models.

def __str__(self):

    return  self.stuname

It will become:

This can be added on the admin page. Delete, modify, query operations.

\

Customize the management page

Create custom managed classes in admin.py

Note: the list_display name can only be written with this name.

Our admin page would be:

The view views

Implement browser access to 127.0.0.1:8080/index, display: I am index page.

Write in the view:

# import module

from django.http import HttpResponse

To define an index method, you must have an argument.

def index(request):

Return HttpResponse(‘ I am the index page ‘)

Create a urls.py in the student directory and say:

from django.conf.urls import url

from student import views

# Set up a correspondence with the view, urlPatterns do not change

The first is a re that matches the returned page

urlpatterns = [

    url(r’^index$’, views.index),

]

Modify urls.py in test1 query:

Modify urlPatterns to:

urlpatterns = [

    url(r’^admin/’, include(admin.site.urls)),

Url (r’^’, include(‘student.urls’)), # let its route support urls under student

]

Can.

For clarity, the browser types 127.0.0.1:8080/index, and the server passes the index to the TEST1 URL, matches the re, and matches the second match in student urls to complete the method mapping.

The template

1. Create a Templates folder

2. In the configuration file (setting.py), set the directory for the website template

Find a list of: TEMPLATES in setting.py,

Change DIRS to:

‘DIRS’:[os.path.join(BASE_DIR,’templates’)]

# os.path.join() path concatenation, BASE_DIR relative path of the project.

3. Go to templates and create a stuinfo folder and an HTML file that says:

4. Return to this page in views

Load the template, equivalent to reading the file

loader.get_template(‘stuinfo/index.html’)

Give the template file data

The first parameter is request, and the second parameter is dictionary

context = RequestContext(request, {})

# Combine the above two to generate an HTML

ret_html = temp.render(context)

# return to browser

return HttpResponse(ret_html)

A visit to 127.0.0.1:8000/index now returns a template file.

From the above we know: we visit different pages in the views of the template is different, different parameters.

We can write our own method to facilitate our operation.

After doing so, we can still access the code, but we dont need to write it. It is already wrapped in Django.

Let’s just write it as:

We can get the same effect as we did before.

4. How to use the parameter dictionary in views?

For example, we return the value:

def index(request):

Call the above method

Return render(request, ‘stuinfo/index.html’,{‘context’:’ I am a parameter ‘})

Receive in index.html:

# Two curly braces with the variable name in the middle

{{ context}}

So our data gets passed through.

Use the for loop in index.html:

We pass in a list

def index(request):

Call the above method

Return render(request, ‘stuinfo/index.html’,{‘context’:’ stuinfo ‘,’list’:list(range(10))})

It’s easy to loop out in index.html

# Start the for loop

{% for i in list%}

{{i}}

# knot number for loop

{% endfor %}

Can.

\

§ § \

Python Chinese community as a decentralized global technology community, to become the world’s 200000 Python tribe as the vision, the spirit of Chinese developers currently covered each big mainstream media and collaboration platform, and ali, tencent, baidu, Microsoft, amazon and open China, CSDN industry well-known companies and established wide-ranging connection of the technical community, Have come from more than 10 countries and regions tens of thousands of registered members, members from the Ministry of Public Security, ministry of industry, tsinghua university, Beijing university, Beijing university of posts and telecommunications, the People’s Bank of China, the Chinese Academy of Sciences, cicc, huawei, BAT, represented by Google, Microsoft and other government departments, scientific research institutions, financial institutions, and well-known companies at home and abroad, nearly 200000 developers to focus on the platform.

Further reading

\

Use Python to crawl the phone APP\

\

30 lines of code to achieve wechat automatic reply robot \

\

100 lines of code to crawl every Pizza Hut restaurant in the country

\

How to deploy and monitor distributed crawler projects easily and efficiently

\

Douyin little sister video crawler \

\

Email: [email protected]

\

**** Free membership of the Data Science Club ****