Django入门教程01

来源:互联网 发布:erp软件视频介绍 编辑:程序博客网 时间:2024/06/06 02:12

本文参考官方的文档里的Tutorial。

假设你已经安装成功了最新版(1.9.6)的Django。

1. 创建一个django项目

首先进入要创建Django项目的目录

# 创建django项目,项目名字叫mysite$ django-admin startproject mysite

注意
1. 不要使用djangotest作为Project名字。
2. 不建议把代码放置到wwwdocument root目录。

用tree命令来查看目录结构

/mysite │  manage.py │ └─mysite         settings.py         urls.py         wsgi.py         __init__.py

这些文件的简要说明:

  1. mysite/根目录外的目录只是个容器,无所谓叫什么名字。

  2. manage.py: 管理django的命令行工具。

  3. 在mysite/里的目录 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).

  4. mysite/__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.

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

  6. mysite/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.

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

2. 开发用服务器

在django开发阶段,我们不需要额外的准备一个服务器,可以直接用django自带的一个服务器来开发。

# 运行django开发服务# 进入项目的根目录,也就是包含manage.py的mysite目录$ cd mysite$ python manage.py runserver  # 也可以指导ip和端口# $ python manage.py runserver 8080# $ python manage.py runserver 0.0.0.0 8080

如果没有任何错误,这个时候在浏览器中访问http://127.0.0.1:8000就应该可以看到Welcome to Django的页面了。

3. 创建第一个django app

我们假设这个app的名字叫polls

# 然后进入mysite目录,创建app$ python manage.py startapp polls

使用tree命令,可以看到:

/mysite/polls │  admin.py │  apps.py │  models.py │  tests.py │  views.py │  __init__.py │ └─migrations         __init__.py

4. 编写第一个views

polls/views.py中,添加下列代码。

from django.http import HttpResponsedef index(request):    return HttpResponse("Hello World. You're at the polls index")

然后,我们在polls/下添加一个文件urls.py,在这个urls.py文件中,添加:

from django.conf.urls import urlfrom . import viewsurlpatterns = [    url(r'^$', views.index, name='index')]

接着,在mysite/urls.py里,添加:

from django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [    url(r'^polls/', include('polls.urls')),    url(r'^admin/', admin.site.urls),]

如果一切都没有问题,在浏览器中,访问http://127.0.0.1:8000/polls/就可以显示。

显示第一个django页面

0 0
原创粉丝点击