Django自学笔记 1-1 新建项目

————总目录——前言——框架版本————

======================= 大爽歌作,made by big shuang =======================

一 新建项目

1- 命令行新建Django项目

新建项目命令(project_name处为项目名)

django-admin startproject project_name

有报错的话,查看Problems running django-admin.

具体来说,选择一个文件夹(假设名为root),在该文件夹里打开命令窗口,新建一个名为demo1的项目,则命令行输入如下:

django-admin startproject demo1

此时会在root下建立一个demo1文件夹,root文件夹结构如下

root:
|——demo1/
	|——manage.py
	|——demo1/
		|——__init__.py
        |——settings.py
        |——urls.py
        |——wsgi.py

各个文件夹文件的官方详细说明如下

  • The outer demo1/ root directory is just a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.

  • manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin and manage.py.

  • The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls).

  • demo1/init.py: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.

  • demo1/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.

  • demo1/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher.

  • demo1/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.

一般来说,manage.pydemo1/__init__.pydemo1/wsgi.py都不要改动,也不用管。
主要是demo1/settings.pydemo1/urls.py需要修改。
settings.py是设置这个Django项目的
urls.py 用于给这个Django项目申明路由的
对于新手而言,看到外层文件夹和内层文件夹同名常常会感到很奇怪很迷惑。不管就好。
新建应用(app)命令(app_name处为项目名)

py manage.py startapp app_name

具体来说,此时应该选择项目文件夹(外层的demo1文件夹),在该文件夹里打开命令窗口
新建一个名为myapp的项目,则命令行输入如下:

py manage.py startapp myapp

此时会在demo1下建立一个myapp文件夹,demo1文件夹结构如下

demo1
|——manage.py
|——demo1/
|	|——__init__.py
|       |——settings.py
|       |——urls.py
|       |——wsgi.py
|——myapp/
    |——__init__.py
    |——admin.py
    |——apps.py
    |——migrations/
        __init__.py
    |——models.py
    |——tests.py
    |——views.py

myapp里面的文件暂时都先不用管, 后面会一点一点介绍。(一般按顺序会先介绍views.py,然后是models.py,之后是apps.py及其他)

2- 使用Pycharm新建Django项目

新建项目
File->New Project后,Pycharm弹窗窗口应如下
在这里插入图片描述
点击左侧侧边栏的第二行的Django,默认参数应该是如下图
在这里插入图片描述
一般直接点击Create就好
如果要新建app的话,可以在上面的Application name处设置, 例如设置为myapp。这样子就不用了进去后再新建app了。
不然进去后如果想新建app只能在通过之前的命令行去新建了。

3- 运行项目

命令行运行服务器
在项目文件夹中打开命令行

py manage.py runserver

对于什么都没有的新项目
此时访问

http://127.0.0.1:8000/

打开网页如下图
在这里插入图片描述
在命令行中,用Ctrl-C关闭服务器。
通过Pycharm来运行
Pycharm会自动针对Django项目添加一个可以运行的服务器配置
直接点击这里就可以运行了
在这里插入图片描述
运行后,点击这个红色的方块,即可关闭服务器。
在这里插入图片描述

上一篇: Django自学笔记0-2 框架版本与相关工具

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章