A Djangao Primer
Today's web sites are actually rich apps (rich application), just like a mature desktop application. Python provides a set of excellent tools for developing Web applications. In this chapter, you will learn how to use Django (http://djangoproject.com/) to develop a project called "Learning Notes" (learning log), an online journaling system that allows you to record the knowledge you have learned about a particular topic. We will develop a specification for this project and then define the model for the data used by the application. We'll use Django's management system to enter some initial data, and then learn to write views and templates so that Django can create pages for our site.
Django is a web framework-a set of tools to help develop interactive Web sites. Django can respond to Web requests and make it easier for you to read and write databases, manage users, and more.
1 Preparation 1.1 Setting up a virtual environment
To use Django, you first need to create a virtual work environment. A virtual environment is a place in the system where you can install packages and isolate them from other Python packages. Separating the project's library from other projects is beneficial, and it is necessary to deploy the learning notes to the server later.
Create a new directory for the project, name it Learning_log, and then switch to the directory in the terminal, creating a virtual environment. If you are using Python 3, you can use the following command to create a virtual environment:
learning_log$ python-m venv ll_env
1.2 Activating a virtual environment
After you establish a virtual environment, you need to activate it using the following command:
Command Ll_env\scripts\activate
1.3 Installing Django
(ll_env) learning_log$ pip install Django
The above three steps on my computer operate as:
1.4 Creating a project in Django
In the case of a virtual environment that is still active (ll_env is enclosed in parentheses), execute the following command to create a new project:
(ll_env) learning_log$ django-admin.py startproject Learning_log.
(ll_env) learning_log$ ls
Learning_log ll_env manage.py
? (ll_env) learning_log$ ls learning_log
__init__.py settings.py urls.py wsgi.py
django-admin.py startproject Learning_log. Let Django create a new project named Learning_log. The period at the end of this command allows the new project to use the appropriate directory structure so that the application can be easily deployed to the server after development is complete.
Running the command ls (dir on the Windows system), the result is that Django has created a new directory named Learning_log. It also creates a file named manage.py, which is a simple program that takes commands and gives them to the relevant part of Django to run. We will use these commands to manage tasks such as working with databases and running servers.
The directory Learning_log contains 4 files, the most important of which are settings.py, urls.py, and wsgi.py. File settings.py Specifies how Django interacts with your system and how to manage the project. During the development of the project, we will modify some of these settings and add some settings. File urls.py tells Django which Web pages should be created in response to browser requests. The file wsgi.py helps Django provide the file it creates, which is the acronym for Web Server Gateway Interface (Web servers gateways interface). Such as:
1.5 Creating a Database
Django stores most of the project-related information in the database, so we need to create a database for Django to use. To create a database for the project "Learning Notes", execute the following command in the active virtual environment:
(11_env) d:\study\python\code\learning_log> python manage.py Migrate
Such as:
We will modify the database as a migration database. The first time you execute a command migrate, Django will make sure that the database matches the current state of the project. When this command is first executed in a new project using SQLite, which is described in more detail later, Django will create a new database. Django states that it will create the necessary database tables to store the information we will use in this project (Synchronize unmigrated apps, synchronizing the non-migrated applications), and then ensure that the database structure is in line with the current code (Apply all migrations, Apply all migration) matches. Django has created a file--db.sqlite3. SQLite is a database that uses a single file, and is ideal for writing simple applications because it lets you not focus too much on database management issues.
1.6 Checking Items
Here's a check to see if Django created the project correctly. To do this, execute the command runserver as follows:
Django launches a server that allows you to view the projects on your system to see how they work. When you enter a URL in a browser to request a Web page, the Django server responds by generating the appropriate Web page and sending it to the browser.
Now open a Web browser and enter Url:http://localhost:8000/; if that doesn't work, enter http://127.0.0.1:8000/. Such as:
2 Creating an Application
A Django project consists of a series of applications that work together to make the project a whole. We only create one application for the time being and it will do most of the work of the project. Later, we will add an application to manage user accounts.
Currently, the Runserver should still be running in the previously opened terminal window. Please open a terminal window (or tab) and switch to the directory where the manage.py is located. Activate the virtual environment, and then execute the command startapp:
D:\study\python\code\learning_log>d:\study\python\code\learning_log\11_env\scripts\activate (11_env) D:\study \python\code\learning_log>dir Volume in drive D was New Volume Volume Serial number is 98c0-1aea Directory of D:\study\p ython\code\learning_log01/02/2018 04:11 pm <DIR>. 01/02/2018 04:11 pm <DIR>.. 01/02/2018 03:56 pm <DIR> 11_env01/02/2018 04:11 pm 131,072 db.sqlite301/02/2018 04:11 pm <DIR> learning_log01/02/2018 04:02 PM 559 manage.py 2 File (s) 131,631 Bytes 4 Dir (s) 955,714,387,968 bytes free (11_env) D:\study\python\code\learning_log>python manage.py St Artapp learning_logs (11_env) d:\study\python\code\learning_log>dir Volume in drive D-is New Volume Volume Serial number is 98c0-1aea Directory of d:\study\python\code\learning_log01/02/2018 04:31 PM <DIR>. 01/02/2018 04:3 1 PM <DIR>. 01/02/2018 03:56 pm <DIR> 11_env01/02/2018 04:11 pm 131,072 db.sqlite301/02/2018 04:11 pm <dir& Gt learning_log01/02/2018 04:31 pm <DIR> learning_logs01/02/2018 04:02 pm 559 manage.py 2 File (s) 131,631 bytes 5 Dir (s) 955,714,383,872 bytes free (11_env) D:\study\python\code\ Learning_log>dir learning_logs Volume in drive D was New Volume Volume Serial number is 98c0-1aea Directory of D:\study\ python\code\learning_log\learning_logs01/02/2018 04:31 pm <DIR> 01/02/2018 04:31 pm <DIR> .. 01/02/2018 04:31 pm 04:31 pm admin.py01/02/2018 apps.py01/02/2018 04:31 pm <D Ir> migrations01/02/2018 04:31 pm models.py01/02/2018 04:31 pm TESTS.PY0 1/02/2018 04:31 pm views.py01/02/2018 04:31 PM 0 __init__.py 6 File (s) Bytes 3 Dir (s) 955,714,383,872 bytes free (11_env) d:\study\python\code\learning_log>
Command Startapp AppName Let Django build the infrastructure needed to create the application. If you look at the project directory now, you will see a new folder Learning_logs. Open this folder to see what Django has created. The most important of these documents are models.py, admin.py and views.py. We will use models.py to define the data we want to manage in the application. admin.py and views.py will be introduced later.
2.1 Defining the Model
Let's think about the data involved. Each user needs to create many topics in the learning notes. Each entry entered by the user is associated with a specific topic, and the entries are displayed as text. We also need to store the timestamp of each entry so that we can tell the user when each entry was created.
From django.db import models# Create your models Here.class Topic (models. Model): ' user learns the subject ' ' Text = models. Charfield (max_length=200) date_added = models. Datetimefield (auto_now_add=true) def __str__ (self): "Returns the string representation of the model" ' Return Self.text
(1) Import the module models and let's create our own model. The model tells Django how to handle the data stored in the application. At the code level, the model is a class that contains properties and methods just like each of the classes discussed earlier.
(2) The topic class, which inherits a class that defines the basic functionality of the model in Model--django. The topic class has only two properties: Text and date_added.
2.2 Activating the Model
To use the model, you must have Django include the application in the project. To do this, open settings.py (which is in directory Learning_log/learning_log) and you will see a fragment that tells Django which applications are installed in the project:
# application Definitioninstalled_apps = [' django.contrib.admin ', ' Django.contrib.auth ', ' django.contrib.content Types ', ' django.contrib.sessions ', ' django.contrib.messages ', ' django.contrib.staticfiles ', #我的应用程序 ' Learni Ng_logs ']
This is a tuple that tells the Django project which applications are made up of. Please add in Installed_apps:
#我的应用程序 ' Learning_logs '
Next, you need to let Django modify the database so that it can store information related to model topic. To do this, execute the following command in the terminal window:
(11_env) D:\study\python\code\learning_log>python manage.py makemigrations learning_logsmigrations for ' learning_logs ': learning_logs\migrations\0001_initial.py -Create model Topic (11_env) D:\study\python\code\learning_log >
The command makemigrations let Django determine how to modify the database so that it can store the data associated with the new model that we define. The output indicates that Django has created a migration file named 0001_initial.py that will create a table for the model topic in the database. To apply this migration, let Django modify the database for us:
Most of the output of this command is the same as the output we executed the command migrate for the first time. What we need to check is the last output line, where Django confirms that it's OK for the Learning_logs app to migrate, and every time you need to modify the "Learning notes" management data, take the following three steps: Modify models.py; to Learning_ Logs call makemigrations; Let Django migrate the project.
2.3 Django Administration site
When you define a model for an application, the Django-provided administration site (admin sites) makes it easy to work with the model. The administrator of the site can use the Administration Web site, but ordinary users cannot use it. In this section, we will build a management site and use it to add some topics using Model topic.
2.3.1 Creating super users
Django allows you to create users with all the privileges-superuser. Permissions determine what actions a user can perform. To create a superuser in Django, follow the instructions below and follow the prompts:
The password is: admin123456
2.3.2 registering a model with the Web site
Django automatically adds some models to the admin site, such as user and group, but it must be registered manually for the model we created. When we created the application Learning_logs, Django created a file named admin.py in the directory where models.py is located, and for registering topic with the administration site, enter the following code:
From Django.contrib import admin# Register your models here.from learning_logs.models import Topicadmin.site.register ( Topic)
The code imports the model topic that we want to register, and then uses Admin.site.register () to let Django manage our model through the administration site. Now, use the Super user account to access the admin site: Access http://localhost:8000/admin/and enter the user name and password of the superuser you just created, which allows you to add and modify users and user groups, You can also manage data related to the model topic that you just defined.
2.3.3 Adding a Theme
Click Topics to go to the theme page, which is almost empty, because we haven't added any topics yet. Click Add, and you'll see a form for adding a new theme. Enter chess in the first box, and then click Save, which will return to the topic Management page, which contains the topic you just created. Create a topic below so that more data is available for use. Click Add again and create another theme, rockclimbing. When you click Save, you'll be back to the topic Management page, which contains the theme chess and rock climbing. Such as:
2.4 Defining the Model entry
To document the learning of chess and rock climbing, you need to define a model for the entries that users can add to their learning notes. Each entry is associated with a specific topic, which is called a many-to-one relationship, where multiple entries can be associated to the same topic. Here is the code for model entry:
From django.db import models# Create your models Here.class Topic (models. Model): ' user learns the subject ' ' Text = models. Charfield (max_length=200) date_added = models. Datetimefield (auto_now_add=true) def __str__ (self): "Returns the string representation of the model" ' Return self.textclass Entry ( Models. Model): ' learned specific knowledge about a topic ' ' topic = models. ForeignKey (topic,on_delete=models. CASCADE) Text = models. TextField () date_added = models. Datetimefield (auto_now_add=true) class Meta: verbose_name_plural = ' entries ' def __str__ (self): "" " returns the string representation of the model" "" return self.text[:50] + "..."
This sentence of the book date_added = models. Datetimefield (auto_now_add=true) will error, change to the above can.
2.5 Migration Model
Since we have added a new model, we need to migrate the database again. You'll know the process slowly: Modify the models.py, execute the command python manage.py makemigrations app_name, and then execute the command pythonmanage.py migrate.
2.6 Registering with the Administration Website entry
We also need to register the model entry. To do this, you need to modify the admin.py to resemble the following:
From Django.contrib import adminfrom learning_logs.models import Topic, Entryadmin.site.register (Topic) Admin.site.register (Entry)
Return to http://localhost/admin/and you will see the entries listed under Learning_logs. Click the Add link for entries, or click entries and select Add entry. You'll see a drop-down list that lets you choose which theme you want to create an entry for, and a text box for entering entries. Select Chess from the drop-down list and add an entry. Here is the first entry I added.
Then create a chess entry and create a rock climbing entry to provide some initial data. Here is a second chess entry. These three entries provide us with the data we use when we continue to develop "learning notes".
2.7 Django Shell
Once you have entered some data, you can view the data programmatically through an interactive terminal session. This interactive environment, called the Django Shell, is the ideal place to test projects and troubleshoot them. The following is an example of an interactive shell session:
When executed in an active virtual environment, the command Python manage.py Shell launches a Python interpreter that you can use to explore the data stored in the project database.
Let's write about it here today, and keep studying!
Python Project Practice Three (Web application) first article