django入门教程 创建项目(Project)和应用(App)

标签:, ,
来源: 老季博客
日期: 2019-9-12
作者: 腾讯云/服务器VPS推荐评测/Vultr
阅读数: 57

创建项目

打开Anaconda Prompt,cd 到一个你想放置你代码的目录,然后运行以下命令:

django-admin startproject jsite

让我们看看 startproject 创建了些什么:

jsite/
    manage.py
    jsite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

创建数据库

打开PyCharm,新建project,目录输入刚创建的jsite,忽略非空目录提示,直接点Yes。打开Terminal窗口,运行以下命令:

python manage.py migrate

会看到类似下面的显示:

D:\jsite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... 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 auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

安装项目

settings.py INSTALLED_APPS 中添加项目名 jsite (需与 apps.py 中的名称一致)

django入门教程 创建项目(Project)和应用(App)

运行用于开发的简易服务器

Terminal窗口中运行以下命令:

python manage.py runserver

会看到类似下面的显示:

D:\jsite>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
October 24, 2018 - 21:53:21
Django version 2.1.2, using settings 'jsite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

浏览器打开http://127.0.0.1:8000/,看到“The install worked successfully! Congratulations!”字样说明成功。千万不要 将这个服务器用于和生产环境相关的任何地方。这个服务器只是为了开发而设计的。

会自动重新加载的服务器 runserver

用于开发的服务器在需要的情况下会对每一次的访问请求重新载入一遍 Python 代码。所以你不需要为了让修改的代码生效而频繁的重新启动服务器。然而,一些动作,比如添加新文件,将不会触发自动重新加载,这时你得自己手动重启服务器。


创建投票应用

请确定你现在处于 manage.py 所在的目录下,然后运行这行命令来创建一个应用:

python manage.py startapp polls

这将会创建一个 polls 目录,它的目录结构大致如下:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py
链接到文章: https://jiloc.com/46311.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注