Django
基本操作
- 创建一个 Django 项目: django-admin startproject sitename
- 创建一个 app: python manage.py startapp web
- 运行: python manage.py runserver 127.0.0.1:8000
Django 处理请求流程
- 在 settings.py 中添加创建的 app
- urls.py 映射 URLpattern: URLpattern --> app.func
- views.py 中 使用 render() 渲染模板 (templates) 并返回结果
- 配置静态文件
- 在 django 项目中创建 static 作为静态文件夹
- 在 settings.py 中添加静态文件目录路径
-
STATIC_URL = ‘/static/‘ STATICFILES_DIRS = ( os.path.join(BASE_DIR, ‘static‘), )
- 在模板中引用
-
<script src="/static/xxx.js"></script>
Views and URLconfs
To design URLs for an application, you create a Python module called a URLconf. Like a table of contents for your app, it contains a simple mapping between URL patterns and your views.
urls.py
from django.conf.urls import url from cmdb import views urlpatterns = [ url(r‘^index/‘, views.index), # mapping URL patterns and views ]
views.py
a view is responsible for doing some arbitrary logic, and then returning a response.
from django.shortcuts import HttpResponse def index(request): return HttpResponse(‘hello world‘)
Templates
With Django’s template system, we can separate the design of the page from the Python code itself. A Django template is a string of text that is intended to separate the presentation of a document from its data. Usually, templates are used for producing HTML, but Django templates are equally capable of generating any text-based format.
- Any text surrounded by a pair of braces (e.g., {{ person_name }}) is a variable.
- Any text that’s surrounded by curly braces and percent signs (e.g., {% if ordered_warranty %}) is a template tag.
- for tag:
-
{% for item in item_list %} <li>{{ item }}</li> {% endfor %}
- if tag:
-
{% if ordered_warranty %} <p>Your warranty information will be included in the packaging.</p> {% else %} <p>You didn‘t order a warranty, so you‘re on your own when the products inevitably stop working.</p> {% endif %}
- filter
-
<p>Thanks for placing an order from {{ company }}. It‘s scheduled to ship on {{ ship_date|date:"F j, Y" }}.</p>
In this example, {{ ship_date|date:"F j, Y" }}, we’re passing the ship_date variable to the date filter, giving the date filter the argument "F j, Y".
Here is the most basic way you can use Django’s template system in Python code:
- Create a Template object by providing the raw template code as a string.
- Call the render() method of the Template object with a given set of variables (the context). This returns a fully rendered template as a string, with all of the variables and template tags evaluated according to the context.
-
from django.shortcuts import render USER_INPUT = {} def index(request): """get submit""" if (request.method == ‘post‘): user = request.POST.get(‘user‘, None) # None is default value email = request.POST.get(‘email‘, None) temp = {‘user‘: user, ‘email‘: email} USER_INPUT.append(temp) """ template loading: t = template.Template(‘My name is {{ name }}.‘) context creation: c = template.Context({‘name‘: ‘Adrian‘}) template rendering: t.render(c) HttpResponse creation """ return render(request, ‘index.html‘, {‘data‘: USER_INPUT})
render()
Django provides a shortcut that lets you
1. load a template 加载模板
2. render it and return an HttpResponse 渲染
all in one line of code.
Models
Django’s database layer.
models.py
from django.db import models # Create your models here. class UserInfo(models.Model): user = models.CharField(max_length=32) email = models.CharField(max_length=32)
create databases:
python manage.py makemigrations
python manage.py migrate
509 garyyang:mysite_django$ python3 manage.py makemigrations Migrations for ‘cmdb‘: cmdb/migrations/0001_initial.py: - Create model UserInfo 511 garyyang:mysite_django$ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, cmdb, contenttypes, sessions Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying cmdb.0001_initial... OK Applying sessions.0001_initial... OK