Django入门教程01
来源:互联网 发布:erp软件视频介绍 编辑:程序博客网 时间:2024/06/06 02:12
本文参考官方的文档里的Tutorial。
假设你已经安装成功了最新版(1.9.6)的Django。
1. 创建一个django项目
首先进入要创建Django项目的目录
# 创建django项目,项目名字叫mysite$ django-admin startproject mysite
注意
1. 不要使用django
或test
作为Project名字。
2. 不建议把代码放置到www
的document root
目录。
用tree命令来查看目录结构
/mysite │ manage.py │ └─mysite settings.py urls.py wsgi.py __init__.py
这些文件的简要说明:
mysite/根目录外的目录
只是个容器,无所谓叫什么名字。
manage.py
: 管理django的命令行工具。
在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).
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.
mysite/settings.py
: Settings/configuration for this Django project. Django settings will tell you all about how settings work.
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.
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入门教程01
- django入门教程
- Django入门教程
- 【python Django】django入门教程1
- django入门教程(一)
- Django 缓存入门教程
- python django快速入门教程
- [django]入门教程4:操作数据库
- 【python入门教程】Django的安装和入门
- Django REST framework 的快速入门教程
- [django]入门教程3:模板语法及使用
- [django]入门教程1:安装配置并创建项目
- django入门教程(二)简单的博客系统
- Django-01
- Hibernate入门教程01
- Scrapy入门教程-01实验
- 机器学习入门教程01
- 01-Python入门教程完整版
- POJ 3714 Raid
- 位运算(C/C++)
- 307. Range Sum Query - Mutable
- windows 7 禁用后台自启软件
- Photoshop:1 - 光和色
- Django入门教程01
- C++模板学习总结
- Makefile简单总结
- SPI的算法
- 剑指offer 15题 【代码的鲁棒性】链表中倒数第k个结点
- Remainders Game
- AS中快捷将json数据生成bean
- 2016-07-09Cpp_jianjie
- 查找算法练习一(线性查找+折半查找)