In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "what is the role of Django", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what is the role of Django" this article?
Django is a free and open source Web framework developed with Python, which can be used to quickly build high-performance, elegant websites! The frame mode of MVC is adopted, that is, model M, view V and controller C, which can also be called MVT mode, model M, view V, template T. Summarize and share what you have learned in the process of learning Django, and review the old and know the new. it would be better if you can help students who want to learn Django but don't know how to start. Preparatory work before the start
1. Build a virtual environment
With the accumulation of our projects, sometimes different projects need not to use different versions of packages, which may lead to conflicts. At this time, we need a virtual environment to separate the packages needed by each project, so that conflicts can be effectively avoided.
2. Install MySql
Django supports many types of databases, the default configuration of sqlite3, we used Mysql in the learning process
3. Install Python3, pip, PyCharm
Python2.X is no longer supported in Django2.0 and later versions, so we need to install the Python3.6 version of the interpreter.
Pip is a general Python package management tool that can find, install, and uninstall packages.
PyCharm is a kind of Python IDE, wall crack is recommended.
For the above preparation work, friends can find relevant tutorials on the Internet.
Preliminary study on Django
Through preparation work, we have installed pip on our system, and by using pip to install the latest version of Django.
Pip3 install django
After installation, we can view the current Django version through python3-m django-- version
(django_venv) xxxAir:djangoDemo xxx$ python3-m django-- version
2.1.3
Create a Django project
1. We can create a project by entering the command line at the terminal
My project here is called djangoDemo.
Django-admin.py startproject djangoDemo
2. You can also create it through the create new project of pycharm
View the directory structure of the Django project
Switch the terminal to the directory to which the project belongs, and use the tree command to view the project structure
Mac installation tree: brew install
Ubuntu installation tree: sudo apt-get install tree
Centos installation tree: sudo yum-y install tree
Execute "tree + Project name"
Tree djangoDemo
DjangoDemo/
├── djangoDemo
│ ├── _ _ init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
Catalog description:
1. DjangoDemo/djangoDemo: the original Python package of the project
2. DjangoDemo/__init__.py: an empty file that declares that the package in the directory is a Python package
3. DjangoDemo/settings.py: manage the configuration information of the project
4. DjangoDemo/urls.py: declare the mapping relationship of the request url
5. DjangoDemo/wsgi.py: communication protocol between python program and web server
6. Manage.py: a command-line tool for interacting with Django projects, such as the file used in the previous project creation.
Project profile-setting.py
The setting.py file is used to configure the entire project, and there are many fields in it, so it is necessary to know what the default configuration is before you begin.
Import os
# the relative path of the project. The manage.py of the path where the file is located will be run when the service is started.
BASE_DIR = os.path.dirname (os.path.dirname (os.path.abspath (_ _ file__)
# Security key
SECRET_KEY = 'lumbago vroomnpes (! j82roomx (44vtroomhindag7io2x) shnf * 9 ^ 8fv0d63! 0r'
# whether to enable Debug
DEBUG = True
# allowed access to the host ip, you can use the wildcard character *
ALLOWED_HOSTS = []
# Application definition
# used to register App. The first 6 apps are included with django.
INSTALLED_APPS = [
'django.contrib.admin'
'django.contrib.auth'
'django.contrib.contenttypes'
'django.contrib.sessions'
'django.contrib.messages'
'django.contrib.staticfiles'
]
# middleware, middleware that needs to be loaded. Such as the method of executing some code according to the rules before the request and after the response
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'
]
# specify URL list file parent URL configuration
ROOT_URLCONF = 'djangoDemo.urls'
# load the path of web page template
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'
]
}
}
]
# configuration file path of WSGI
WSGI_APPLICATION = 'djangoDemo.wsgi.application'
# Database configuration default database is sqlite
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3'
'NAME': os.path.join (BASE_DIR, 'db.sqlite3')
}
}
# related password verification
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'
}
]
# language setting defaults to English, Chinese is zh-hans
LANGUAGE_CODE = 'en-us'
# time zone setting, China is: Asia/Shanghai
TIME_ZONE = 'UTC'
Does the # i18n character set support
USE_I18N = True
USE_L10N = True
# whether to use timezone
# make sure that the UTC time is stored in the database
# when passing time parameters between functions, make sure that time has been converted to UTC time
USE_TZ = True
# static file path
STATIC_URL ='/ static/'
App
Next to introduce a concept of APP, for example, we need to develop an e-commerce website, then product lists, shopping carts, placing orders, etc. These are different lines of business, we can think of each line of business as an App.
Create App
Create an application called app_demo and execute it under the terminal project directory
Python3 manage.py startapp app_demo
Tree again to view the directory structure
├── app_demo
│ ├── _ _ init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ └── _ _ init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── djangoDemo
│ ├── _ _ init__.py
│ ├── _ _ pycache__
│ │ ├── _ _ init__.cpython-36.pyc
│ │ └── settings.cpython-36.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
App_demo directory structure
Admin: corresponding to the application backend management configuration file
Apps: configuration file of the corresponding application
Models: data module for designing databases, etc.
Tests: writing test scripts
Views: view layer, interacting directly with the browser
Each time we create a new App, we need to register it in the INSTALLED_APPS in the settings.py file so that the program can find the service.
INSTALLED_APPS = [
'django.contrib.admin'
'django.contrib.auth'
'django.contrib.contenttypes'
'django.contrib.sessions'
'django.contrib.messages'
'django.contrib.staticfiles'
'app_demo', # register the newly created application app
]
HelloWorld
The beginning of any language in helloworld, so our entry-level program also starts here. As mentioned earlier, Django frame MVT structure, here because there is no data and templates, so only need to do coding in V (view layer).
Open view.py under the app_demo directory and start coding
From django.http import HttpResponse
"
The API of the HttpResponse object is defined in the django.http module
Function: no need to call the template to return data directly
HttpResponse attribute:
Content: return content, string type
Charset: the coded character set of the response
Status_code: the status code of the HTTP response
"
"
Hello is a view function, and the first argument of each view function must be request. Even if you don't need request.
Request is an instance of django.http.HttpRequest
"
Def hello (request):
Return HttpResponse ('Hello World')
The view layer is written, and finally 'Hello World'' is responded to by HttpResponse.
As mentioned earlier, urls is used to declare the mapping of the request url. That is, the program finds the view we wrote through the configuration in urls.
# Import url module
From django.conf.urls import url
Urlpatterns = [
Path ('admin/', admin.site.urls)
Url (r'^ hello/$', views.hello)
]
The above code is added to the view file under djangoDemo
From django.conf.urls import url
Url (r'^ hello/$', views.hello)
Add url ('hello/', views.hello) to the urlpatterns, the first element is the matching string, and the second element is the corresponding view module.
That is, tell django that all url/hello/ requests point to the views.hello view. There is no need to add'/ 'before hello, because there must be a' /'at the end of the domain name. Where'^'is a strict pre-match and'$'is a strict post-match. If no $is added, the browser can also access the view.hello view by typing http://localhost:8000/hello/a/b
And a chestnut.
Continue to add to the views module of app_demo (same as the hello view written earlier)
Def msg (request, name, age):
Return HttpResponse ('My name is'+ name +', I am'+ age + 'years old')
The app_demo app in setting has been registered before, so there is no need to register again. Configure their relationship mapping in urls.
Urlpatterns = [
Path ('admin/', admin.site.urls)
Url (r'^ hello/$', views.hello)
Url (r'^ msg/ (? P\ w+) / (? P\ d +) / $', views.msg)
]
This is to match our url by regularization. (? P\ w +) indicates that the value range of the name field is a non-numeric character, that is, Amurz Amurz Chinese character, (? P\ d +) means that the age field can only be a number.
Start the project
Start the project by executing the following command
Python3 manage.py runserver
The default port number is 8000. When port 8000 is occupied, we can also change the port manually, such as 8080.
Python3 manage.py runserver 8080
If you enter something in the console, it indicates that the startup is successful:
Performing system checks...
System check identified no issues (0 silenced).
You have 15 unapplied migration (s). Your project may not work properly until you apply the migrations for app (s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
November 08, 2018-05:34:59
Django version 2.1.3, using settings' djangoDemo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Project launched successfully browser input
Http://localhost:8000/hello/, we can see the following interface
Browser input http://localhost:8000/msg/tome/12/
These are all the contents of this article "what is the purpose of Django?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.