Web application of python application chapter - Django introduction (middle)

foreword

  Starting from the last article , I will introduce you to the introduction of Django, a set of tools used to help develop interactive websites. Django can respond to website requests, and it also makes it easier for you to read and write databases, manage users, and more. It mainly includes formulating specifications, establishing virtual environments, installing virtualenv, activating virtual environments, installing Django, and creating projects in Django, creating databases, and finally viewing projects. This article will introduce you to the relevant content of creating applications.

Create an application

  A Django project is a collection of applications that work together to make the project a whole. For now, we'll just create an application that will do most of the work for the project.
  Currently, it should still be running in the previously opened terminal window runserver. Please open another terminal window (or tab) and change to manage.pythe directory where it is located. Activate the virtual environment and execute the command startapp. The specific execution is as follows:

source ll_env/bin/activate
python manage.py startapp learning_logs
dir
dir learning_logs/

  The result of the specific execution is as follows: The

  command startapp.appnametells Django to set up the infrastructure needed to create the application. If you now look in the project directory, you will see a new folder added to it learning_logs. Open this folder and see what Django has created. The details are as follows:

  The most important documents are models.py, admin.pyand views.py. We will use models.pyto define the data we want to manage in the application. The admin.pysum views.pyof which will be introduced later.

1. Define the model

  Let's think about the data involved. Each user needs to create many topics in study notes. Each entry entered by the user is associated with a specific topic, and these 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.
  Let's open the file models.pyand see what it currently contains:

from django.db import models
# 在这里创建模型

  This imports the module models for us and also lets us create our own models. Models tell Django what to do with the data stored in the application. At the code
level, a model is a class that, like every class discussed earlier, contains properties and methods. Here is the topic model that represents the user will be stored:

class Topic(models.Model):
    """用户学习的主题"""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """返回模型的字符串表示"""
        return self.text

  We created a Topicclass called , which inherits from - a class in ModelDjango that defines the basic functionality of a model. The Topic class has only two properties: textand data_added. Attributes textare one CharField- data made up of characters and text. Useful when you need to store small amounts of text, such as names, titles, or cities CharField. When defining CharFieldproperties, you must tell Django how much space to reserve in the database. Here, we'll max_lengthset it to 200 (200 characters), which is enough to store most subject names.
  A property date_addedis one DateTimeField- data that records the date and time. We pass the argument -- auto_now_add=True, which tells Django to automatically set this property to the current date and time whenever the user creates a new topic.

  One caveat here: To learn about the various fields that can be used in a model, see the Django model fields reference . Right now, we don't need to understand all of them, but they can be extremely helpful when developing applications ourselves.

  We need to tell Django which attribute should be used by default to display information about the theme. Django calls methods __str()__to display simple representations of models. Here, we wrote the method __str__(), which returns the string stored in the property text.

  Something to note here: if we were using Python 2.7, the method should be called __unicode__()instead __str()__, but the code in it is the same.

The activation model

  To use models, you must have Django include the app into your project. To do this, open settings.py(it is located in the directory learning_log/learning_log), we will see a snippet like this, which tells Django which applications are installed in the project, and the location of the specific setting is shown in the figure below:

  The specific settings.pycontent is as follows:

"""
Django settings for learning_log project.

Generated by 'django-admin startproject' using Django 1.11.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'klx8i)7p@fa&jc=(wtc^0l^08p*jfuygqg_+d58h%#4k+e$juh'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'learning_log.urls'

TEMPLATES = [
    {
    
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
    
    
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'learning_log.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    
    
    'default': {
    
    
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
    
    
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
    
    
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
    
    
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
    
    
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

  This is an array that tells Django which applications the project is made of. Please INSTALLED_APPSmodify it as follows, adding the previous application to this tuple:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 添加我们自己的应用
    'learning_logs',
]

  The specific writing positions are shown in the figure below:

  By grouping applications, it is helpful to keep track of applications as the project grows and contains more applications. There is a new My appsfragment called here, which currently only contains the application learning_logs. Next, you need to Djangomodify the database so that it can store information related to the model topic. To do this, execute the following command in a terminal window:

python manage.py makemigrations learning_logs

  The command makemigrationslets Django determine how to modify the database so that it can store the data associated with the new model we define. The output shows that Django created a 0001_initial.pymigration file named migrations that will create a table in the database for the model topic. details as follows:

  Let's apply the migration and let Django modify the database for us:

python manage.py migrate

  Most of the output of this command is the migratesame as the output of our first execution of the command. All we need to check is the corresponding output line, where Django confirms that learning_logseverything is OK when applying the migrations. The specific operation is as follows:

  Whenever you need to modify the data managed by "study notes", the following three steps are taken: modify models.py; learning_logscall makemigrations; let Django migrate the project.

3. Django management website

  When defining models for an application, the admin site provided by Django allows us to easily work with models. The administrator of the website can use the management website, but ordinary users cannot. Next, we'll set up the admin site and use the model topic to add some topics through it.

1. Create a super user

  Django allows us to create users with all privileges - superusers. Permissions determine what a user can do. The most restrictive permission settings only allow users to read public information on the site; registered users can usually read their own private data, as well as some information that only members can see. In order to effectively manage a web application, website owners often need access to all the information the website stores. Good administrators treat sensitive user information with care, because users place great trust in the applications they access.
  To create a user in Django, execute the following command and follow the prompts:

python manage.py createsuperuser
ll_admin

  When we execute the command createsuperuser, Django prompts us for the username of the superuser. Here we enter yes ll_admin, but we can enter any username, such as an email address, or leave this field blank. We need to enter the password twice, the details are as follows: The specific content is as follows:

  The website will let you enter the user name and password after it comes out:

  A word of caution here: some sensitive information may be hidden from webmasters. For example, Django does not store the password we enter, but stores a string derived from that password - the hash value. When we enter the password, Django calculates its hash value and compares the result with the stored hash value. value to compare. If the two hash values ​​are the same, the authentication is passed. By storing the hash value, even if a hacker gains access to the website database, they can only obtain the hash value stored in it, but not the password. With a properly configured website, it is almost impossible to deduce the original password from the hashed value.

2. Register the model with the management website

  Django automatically adds some models to the admin site, such as userand group, but for the models we create, they must be registered manually. When we created the application learning_logs, Django models.pycreated a file named in the directory where it is located admin.py, as follows:

from django.contrib import admin
# 在这里注册你的模板

  To register with the management site Topic, enter the following code:

from django.contrib import admin
from learning_logs.models import Topic, Entry
admin.site.register(Topic)

  This code imports our registered model Topic, and then uses it admin.site.register()to let Django manage our model through the admin site.
  Now, use the superuser account to access the admin site and enter the username and password of the superuser we just created and we will see a screen similar to the one shown below. This website allows us to add and modify users and user groups, as well as manage data related to the model topics we just defined. details as follows:

  Something to note here: if we see a message in the browser that the visited webpage is unavailable, confirm that we have the Django server running in a terminal window. If not, activate the virtual environment, and execute the command python manage.py runserver.

3. Add a theme

  After registering with the admin site Topic, let's add our first theme. To do so, click Topicthrough to the themes page, which is almost empty because we haven't added any themes yet. Click Add and you'll see a form for adding a new theme. Type in the first box Chessand click save, which will return you to the theme management page with the newly created theme.
  Create another topic when it's full to have more data to work with. Click again Addand create another theme Python. When we click save, we will be taken back to the theme management page, which contains themes java and chess.

Fourth, define the modelEntry

  To document learned Python knowledge, you need to define models for entries that users can add to their study notes. Each item is associated with a specific topic. This relationship is called a many-to-one relationship, meaning that multiple items can be related to the same topic. Here is Entrythe code for the model:

class Entry(models.Model):
    """学到的有关某个主题的具体知识"""
    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):
        """返回模型的字符串表示"""
        return self.text[:50] + "..."

  Like Topic, Entryalso inherits the Django base class Model. The first property Topicis an ForeignKeyinstance. A foreign key is a database term that refers to another record in the database; these codes associate each entry to a specific subject. When each topic is created, it is assigned a key (or ID). When a connection needs to be made between two pieces of data, Django uses keys associated with each piece of information. Later we will get all the entries associated with a particular topic based on these connections.
  Next property text, it is an TextFieldinstance. This kind of field doesn't need a length limit because we don't want to limit the length of the entry. Attributes data_addedallow us to render items in the order they were created and placed next to each item.
  Finally, we Entryembed the Metaclass in . MetaStores extra information for managing the model, here it allows us to set a special property to Djangobe used when needed Entriesto represent multiple items. Without this class, Django would use entries to represent this multiple entry. Finally, the method __str__()tells Django what information should be displayed when the entry is rendered. Since the text contained in the entry can be very long, we let Django display only the first 50 characters of the text. We've also added an ellipsis to indicate that not the entire entry is displayed.

5. Migration ModelEntry

  Since we added a new model, the database needs to be migrated again. We'll slowly get to grips with the process: modify models.py, execute the command python manage.py makemigrations app_name, execute the command python manage.py migrate. Let's migrate the database and check the output:

python manage.py makemigrations learning_logs
python manage.py migrate

  A new migration file is generated 0002_entry.py, which tells Django how to modify the database so that it can store information related to model entries. Execute the command migrate, we sent Django to apply this migration and all went well. details as follows:

6. Register with the management websiteEntry

  We also need to register the model Entry. To do this, we need to modify admin.py to look like this:

from django.contrib import admin

from learning_logs.models import Topic, Entry

admin.site.register(Topic)
admin.site.register(Entry)

  Return to http://localhost:8000/adminand you will see learning_logsthe following listed Entries. Click Entriesthe Add link, or click Entriesand select Add entry. details as follows:

  We'll see a drop-down list that allows you to choose which topic to create the entry for, and a text box for entering the entry. Select from the drop-down list Pythonand add an entry. Here is the first entry we added:

  The Python Package Index (PyPI) hosts thousands of third-party modules for Python. Both Python’s standard library and the community-contributed modules allow for endless possibilities.

  When we click save, we will return to the main item management page. Here, we'll use text[:50]the benefit of being a string representation of an item; in the admin interface, only the development part of the item is shown instead of all the text, which makes managing multiple items much easier. The specific process is as follows: The

  created effect is as follows:

  Then create two Python related content, the specific content is as follows:

  The community hosts conferences and meetups, collaborates on code, and much more. Python’s documentation will help you along the way, and the mailing lists will keep you in touch.
  Python can be easy to pick up whether you’re a first time programmer or you’re experienced with other languages. The following pages are a useful first step to get on your way writing programs with Python!

  The effect of the three pieces of data created is as follows:

  When we continue to develop the "study notes", these three entries can provide us with the data to use.

七、Django shell

  Once some data is entered, it can be viewed programmatically through an interactive terminal session. This interactive environment, called the Django shell, is ideal for testing and troubleshooting your project. Here is an example of an interactive shell session:

python manage.py shell
from learning_logs.models import Topic
Topic.objects.all()

  When executed in an active virtual environment, the command python manage.py shellstarts a Python interpreter that can be used to explore data stored in the project database. Here, we import the learning_logs.modelsmodel in the module Topicand then use the method Topic.objects.all()to get Topicall instances of the model; what it returns is a list, called query join. The specific process is as follows:

  We can traverse the queryset like traversing a list. The following demonstrates how to view the ID assigned to each topic object:

topics = Topic.objects.all()
for topic in topics:
	print(topic.id, topic)

  We store the returned queryset in topics, then print the id attribute and string representation of each topic. As you can see from the output, the ID of the topic Python is 3, as follows:

  Once you know the ID of an object, you can get the object and view any of its properties. Let's take a look at the attributes textand date_addvalues ​​of the theme Python, as follows:

t = Topic.objects.get(id = 1)
t.text
t.date_added

  The specific results are as follows:

  we can also view the entries associated with the topic. Earlier we Entrydefined the attribute topic for the model, which is one ForeignKeythat associates an item with a topic. Django can get all the items associated with a specific topic, as follows:

t.entry_set.all()

  The specific results are as follows:

  To obtain data through a foreign key relationship, the lowercase name of the related model, the underscore, and the word set can be used. For example, suppose you have models Pizza and Topping, and Topping is related to Pizza through a foreign key; if we have an object my_pizza, representing a pizza, we can use code my_pizza.topping_set.all()to get all the ingredients for that pizza.
  We will use this syntax when writing user-requestable web pages. The shell is helpful when confirming that the code is getting the data it needs. If the code behaves as expected in the shell, they also work correctly in the project file. If the code throws an error or gets data that is not as expected, it is much easier to troubleshoot in a simple shell environment than in the file that generates the web page. We won't use the shell much, but should continue to use it. Ali is familiar with Django syntax for accessing data stored in projects.

  It should be noted here that after each modification to the play model, we need to restart the shell so that we can see the effect of the modification. To exit the shell, press Ctrl+D; if we are using a Windows system, press Ctrl+Z, and then press Enter.

Summarize

  Starting from the last article , I will introduce you to the introduction of Django, a set of tools used to help develop interactive websites. Django can respond to website requests, and it also makes it easier for you to read and write databases, manage users, and more. It mainly includes formulating specifications, establishing virtual environments, installing virtualenv, activating virtual environments, installing Django, and creating projects in Django, creating databases, and finally viewing projects. This article will introduce you to the relevant content of creating an application, mainly including defining, activating models, Django management website, and defining and migrating model entries and finally the simple use of the Django shell. Python is a practical language, it is the simplest of many programming languages, and it is also the best to get started. When you have learned the language, it is relatively simple to learn java, go and C. Of course, Python is also a popular language, which is very helpful for the realization of artificial intelligence. Therefore, it is worth your time to learn. Life is endless and struggle is endless. We work hard every day, study hard, and constantly improve our ability. I believe that we will learn something. come on! ! !

Guess you like

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