django基础入门学习

2018/12/11 python

django基础入门学习

安装django

pip install Django==2.0.1
python -m django --version

创建一个项目

django-admin startproject mysite

生成的目录结构如下:

mysite/
    manage.py
    mysite/
        __init__.py 告诉python这是一个package
        settings.py django的配置
        urls.py url相关
        wsgi.py 基于wsgi的web服务的入口点

启动开发测试服务器

注意不要用于生产环境

默认8000端口
python manage.py runserver
python manage.py runserver 8080
python manage.py runserver 0.0.0.0:8080

Invalid HTTP_HOST header: '192.168.110.128:5555'. You may need to add '192.168.110.128' to ALLOWED_HOSTS.

vi task/settings.py

ALLOWED_HOSTS = ['192.168.110.128', 'localhost', '127.0.0.1']

创建一个app Creating the Polls app¶

app:通常是一个完成特定功能,如日志系统等 通常一个projects会包含多个app

Projects vs. apps

What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

python manage.py startapp polls

一个app的layout如下:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

修改视图文件 Write your first view¶

vi polls/views.py

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

要访问url,需要路由映射,在polls目录下创建urls.py文件

vi urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

接下来,在根模块下的urls.py文件, task/urls.py文件中,增加如下内容

vi task/urls.py

from django.urls import include, path
from django.contrib import admin

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

include() 函数允许引用其他的url配置,应该使用使用include(),admin.site.urls除外

admin后台

django默认提供admin后台管理

127.0.0.1:5555/admin

使用如下命令创建超级用户

python manage.py migrate
python manage.py createsuperuser

Search

    Table of Contents