If life is just like the first time you see it, why don't you take a look at Django

foreword

This article introduces the basic use of the Django framework, one of the three major web frameworks of python, how to create a django project, how to run a django project and the directory structure of a django project, and how does django return different data and pages?

Three mainstream web frameworks of python

Python has three major web frameworks: Django, flask, and tornado. The following table briefly compares the three frameworks:

Django flask tornado
Full-featured short Asynchronous non-blocking, support high concurrency
sometimes too bulky More dependent on third-party modules ...

django install

Django has 1.x version, 2.x version, and 3.x version. Each version is different. If you do not specify a version, the latest version will be installed by default. Verify that the installation was successful by running at the command line django-admin.

pip install django  # 安装最新版本
pip install django==1.11  # 指定版本安装,版本为1.11

Basic operation of django

The basic operations of Django include creating a Django project, starting a Django project, and creating an application, which are created using the command line and pycharm respectively.

command line operation

The first is to create a Django project. When using the command line to create a Django project, you need to pay attention that you don’t need to open the python interpreter , you can operate directly on the command line. Before creating the project, you can switch the path to the directory you want to create.

django-admin startproject first_django

After successful creation, the file structure under the project folder first_django is as follows:

After successfully creating the project, you can run the Django project. When running the Django project, you need to switch the directory to manage.pythe path where you are and execute the following command:

python manage.py runserver

Another command is to create an application. Here we need to explain the meaning of the application -  an application is simply an independent functional module . For example, a shopping mall project can be divided into order application, user application, commodity application and so on. To create an application, you also need to switch the directory to the path where the manage.py file is located. The command is as follows:

# 应用名需见名知意
# python manage.py startapp 应用名
python manage.py startapp first

Focus! Focus! ! ! After each application is created, it must be registered in the configuration file (settings.py).

# settings.py注册应用部分的代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first.apps.FirstConfig', # 全写,推荐的方式
    'first', # 简写
]

pycharm operation

The pycharm community edition does not support direct creation of Django projects, only the professional edition does. But both the professional and community editions can run Django projects . The professional version of pycharm can directly select Django when creating a Django project.

When pycharm runs the Django project and creates an application, you can run the command directly in the terminal of pycharm:

python manage.py runserver  # 运行django项目
python manage.py startapp first  # 创建应用

The difference between the command line and pycharm to create a django project

There is a little difference between creating a django project on the command line and creating a django project with pycharm. The template folder will not be automatically created when you use the command line to create it. You need to create it manually, but pycharm will automatically create it for you and also automatically in the configuration file. Configure the corresponding path in , which means that when creating a django project with the command, not only need to manually create the templates folder, but also need to configure the path in the configuration file.

# pycharm创建 - settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
      
        'DIRS': [os.path.join(BASE_DIR, 'templates')],       
]

# 命令行创建 - settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
]

Introduction to main documents

Create a django project and create the directory structure and file introduction after the application.

Django framework and custom web framework

In deriving the python web framework, it realizes dividing files and returning different data or pages according to different urls. The django framework can naturally realize the above two "small" functions. What is stored in the django project is deriving the web framework views.pyThe function encapsulated at the time is called a view function, urls.pywhich stores the correspondence between the view function and the route . How does Django return data to the client? You need to use three methods -  HttpResponse, render, redirect, according to the actual code demonstration.

HttpResponse, render, redirect basic use

# HttpResponse - 定义视图函数时返回字符串类型的数据
# views.py
def index(request):
    '''
    :param request: 请求相关的所有数据对象,比之前的env更厉害,后面会介绍request对象
    :return:HttpResponse(返回字符串至浏览器客户端)
    '''
    return HttpResponse('welcome my django!')
    
# urls.py
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/',views.index),
]


------------------------分割线-----------------------------------------------------------
# render - 定义视图函数时,返回HTML页面至浏览器客户端
def index(request):
    '''
    :param request: 请求相关的所有数据对象,比之前的env更厉害,<WSGIRequest: GET '/index/'>
    :return:render(request,'render_html.html'):第一个参数时request,第二个参数时html文档的名字,会自动去template文件夹中找html文档
    '''
    return render(request,'render_html.html')


---------------------------------分割线-------------------------------------------------
# redirect - 定义视图函数时,返回值会将页面进行重定向
def index(request):
    '''
    :param request: 请求相关的所有数据对象,比之前的env更厉害
    :return:redirect,会将网页重定向,可以重定向至网址,也可以重定向到自己项目中的路由(只需要写网页后缀即可)
    '''
    # return redirect('https://www.baidu.com')   # 重定向到百度
    return redirect('/home/')   # 重定向到当前项目中的/home页面

def home(request):
    return HttpResponse('我是自定义的')

Guess you like

Origin blog.csdn.net/nhb687095/article/details/130458503