Django- download and install - Configure - Create django project - three tricks using simple

Django

Official website

Brief introduction

It is designed as a perfectionist web framework

The web framework for perfectionists with deadlines.

django allows you to use less code, more easily and quickly to develop web applications.

Django makes it easier to build better Web apps more quickly and with less code.

Below this is too long, there please Baidu translation:

django is a senior python web framework that encourages rapid development and clean, pragmatic design. Constructed by experienced developers, web development to solve many problems, so you can focus on writing your application, without having to re-create the wheel . It is free and open source is.

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

speak English:

  • Large and comes with features particularly special, similar to an aircraft carrier
  • Cons: sometimes too bulky (small project has many features that comes less than)

Note the use of django

  • The computer name can not be Chinese

  • File naming Try also not to use Chinese

    If the Chinese are likely to cause encoding coding error

  • A pycharm window can have only one item , do not put more on the project next window

  • Note django's version of the problem ... (expanded description below)

  • After starting a django project, must pay attention to port

    Django think of multiple projects, remember to replace the port (port to prevent conflict)

The computer name can not have Chinese

Django version of the problem

Different versions of django course is different, in order to prevent accidental bug, best to use the same version (industry rule: Do not try the latest version)

1.11.11 below to unfold, there may be different versions of different problems

django download and install

Still need to download and install a little bit of time, consider using domestic configuration pip warehouse address

Following installation can be selected from a

Download and install the command line

pip3 install django==1.11.11(1.11.11是版本号)

In pycharm download and install a graphical interface

Be sure to remember to choose the version you need

Verify that the installation was successful

Typing the following command at the command line to

django-admin

Return similar to the following information is to install a bunch of success

Create a Django project

Create and launch the command line

If not, what are you supposed to make you change on the server?

Command line to create django project

django-admin startproject project_name(项目名)

Command line to create django project

Change to the directory first project to be stored and create

An application (App) corresponding to the individual function together

django-admin startapp app01(应用名)

or

python manage.py startapp app01(应用名)

Command line start django project

To cut to the project directory

python manage.py runserver

note

Use the command line to create a django project does not automatically create a new template templates folder , you need to manually create your own needs and path to the file settings.py file registration

Create and start the next pycharm

It can create an application (app) when creating the project, subsequently created via the command line

Follow add app

Command line (to master, may interview ****)

python manage.py startapp app02

Startup project

The green arrow points to start the project (if not to the left of the icon, then their editors under)

If you do not have that icon

The project can not start

If the command line to start the project no problem , but pycharm start not start , please note that the python interpreter whether the election, I have friends that election became pythonw, resulting in django project which does not run up pycharm

You must take wrong to delete, or otherwise the next time defaults to the first one

django project directory Description

+项目名文件
    +应用文件夹(app01)
        +migrations 文件夹     数据库迁移记录
        -admin.py   django后台管理
        -apps.py    应用注册相关
        -models.py  orm表模型类
        -tests.py   测试文件
        -views.py   视图函数/类
    +与项目名同名的文件夹
        -settings.py    django暴露给用户可配置的文件
        -urls.py        路由文件,配置路由与视图函数对应关系
        -wsgi.py        
    +templates      页面模板文件夹,一般放待渲染数据的html页面
        -test.html  待渲染数据的页面(使用django自带的模板语法去渲染)
    -mange.py       django的入口文件
    

New applications (app) special attention*****

Creating an application (app) must be registered in settings where (adding records) take effect (in front of those projects is django own app)

Settings.py configuration file parsing

Intercepting portion Introduction

# ...其他代码...
# Application definition
# 创建的应用一定要在这里注册才能生效
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',  # 规范写法
    'app02',  # 简写
    'app03'
]

# django中间件  django的门户 保安
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 = 'myfirstdjangodemo.urls'


# 模板文件配置相关
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        '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 = 'myfirstdjangodemo.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'),
    }
}
# ...其他代码...

django white will be three tricks

Premise: This is the beginning of a default django project has been created

三板斧:
    HttpResponse:   用来返回字符串给页面
    render:         返回html页面并且能够给该页面传值
    redirect:       重定向,返回指定的页面html(浏览器可以看到302状态码)

He emphasized: each function should be newly added in the routing file urls.pyto add a route to view the correspondence relationship (the time of the request path corresponding to only view function / class to handle)

The most simple steps:

  1. Create app
  2. Configuring routing (routing and view corresponding relationship function)
  3. Write view functions (to use HttpResponse, redirect, remember the guide over)
  4. Writing the Template page

For example HttpResponse

Add Route

first_django_project/urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views  # 导入视图函数文件

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),  # 新添加的路由, index 浏览器端口后面的地址 --> 127.0.0.1地址:8000端口/index, views.index 输入前面地址时将要执行的函数
]

Preparation of the corresponding view function

app01/views.py

from django.shortcuts import render, HttpResponse, redirect
# 引入 HttpResponse(直接返回字符串并打包成响应体返回) 和 redirect(重定向页面)


# Create your views here.
# index 路由对应的视图函数,这里用 HttpResponse 返回一个字符串
def index(request):
    return HttpResponse('<h1>Hello, this is Index!</h1>')  # 可以返回html标签,浏览器依旧会渲染效果

Request data in the browser

127.0.0.1:8000/index/

Example render (render the template data may be transmitted)

Add Route

first_django_project/urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views  # 导入视图函数文件

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^login/', views.login),  # 新添加的 登录路由 与 对应的视图函数
]

Configuration view function

New Page

templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>这是登录页面</h1>
    {# django的模板语法(支持字典 点语法取值 dic.key,但不支持字典的原生语法,这一点不如jinja2(模板引擎语法,一般和flask框架搭配使用) 强大!) #}
    <h3>{{ user_dict.username }}</h3>
</body>
</html>

Add View function

app01/views.py

from django.shortcuts import render, HttpResponse, redirect
# 引入 HttpResponse(直接返回字符串并打包成响应体返回) 和 redirect(重定向页面)


# Create your views here.
def index(request):
    return HttpResponse('<h1>Hello, this is Index!</h1>')


# login 路由对应的视图函数,这里用 render 返回 html 格式的页面字符串
def login(request):
    user_dict = {  # 模拟后台处理好的数据
        "username": "jason"
    }
    # login.html 这里不需要加上templates 文件夹,已经做过配置了,会自动找到的
    # return render(request, 'login.html')  # 可什么数据都不带
    # {"user_dict": user_dict} 包装成响应体返回, 键"user_dict"在模板中可以拿到
    return render(request, 'login.html', {"user_dict": user_dict})

Request data in the browser

redirect Case

The old rules: add routes

first_django_project/urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views  # 导入视图函数文件

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^login/', views.login),
    url(r'^home/', views.home),  # 新添加的 home 路由 与 对应的视图函数(这里是演示重定向,直接跳转到 login路由去处理)
]

Configuration view function

from django.shortcuts import render, HttpResponse, redirect
# 引入 HttpResponse(直接返回字符串并打包成响应体返回) 和 redirect(重定向页面)


# Create your views here.
def index(request):
    return HttpResponse('<h1>Hello, this is Index!</h1>')


def login(request):
    user_dict = {
        "username": "jason"
    }
    return render(request, 'login.html', {"user_dict": user_dict})


def home(request):  # home 路由对应的视图函数
    print("----> 请求home 路径,进入到了 home的路由函数...")
    return redirect('/login/')

Request data in the browser

Just a word printed in the background, to see if there

Figure mark is the latest version of QQ screenshots of new features (feel good, recommended! Ha ha ha)

Guess you like

Origin www.cnblogs.com/suwanbin/p/11515605.html
Recommended