示例:
1、创建一个项目:
$ django-admin startproject website
2、配置数据库
创建数据库 webdemo
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'webdemo', 'USER': 'root', 'PASSWORD': 'xxxxx', 'HOST': 'localhost', 'PORT': '3306', } }
3、验证开发服务器:
$ python manage.py runserver
你将看到命令行下输出了以下内容:
Performing system checks...
0 errors found May 13, 2015 - 15:50:53 Django version 1.8, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
4、创建您的应用程序:
$ python manage.py startapp polls #创建了 polls 应用文件
4.1、创建两个模型: Question和Choice。
polls/models.py
from django.db import models
class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')
class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
4.2、激活应用模型
website/settings.py
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', )
4.3、现在Django知道要包含polls应用。 让我们运行另外一个命令:
$ python manage.py makemigrations polls
你应该看到类似下面的内容:
Migrations for 'polls': 0001_initial.py: - Create model Question - Create model Choice - Add field question to choice
4.4、首先,让我们看一下迁移行为将会执行哪些SQL语句。
$ python manage.py sqlmigrate polls 0001

4.5、现在,再次运行migrate以在你的数据库中创建模型所对应的表:
$ python manage.py migrate
5、创建一个管理员用户
$ python manage.py createsuperuser
键入你想要使用的用户名,然后按下回车键等等。
启动开发服务器:Django的管理站点是默认启用的。
让我们启动开发服务器,然后探索它。
$ python manage.py runserver 127.0.0.1:13709
访问 http://localhost:13709/admin
6、编写你的第一个视图
polls/views.py
from django.http import HttpResponse
def index(request): return HttpResponse("Hello, world. You're at the polls index.")
7、为了能够调用这个视图,我们需要将这个视图映射到URL上 —— 利用一个URLconf。
为了在投票应用目录内部创建URLconf,需要创建一个urls.py文件。
新建 polls/urls.py
在polls/urls.py文件中键入如下代码:
from django.conf.urls import url
from . import views
urlpatterns = [ url(r'^$', views.index, name='index'), ]
下一步,让主 URLconf 可以链接到 polls.urls 模块。
在 website/urls.py 中插入一个include():
from django.conf.urls import include, url from django.contrib import admin
urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), ]
一、创建一个项目:
在命令行(终端)中,cd(例如cd exam)到你想要用来保存代码的目录,然后运行如下命令:
$ django-admin startproject mysite
备注:django中文编码
# coding=utf8
/usr/local/lib/python2.7/dist-packages/django
192.168.40.144
二、开发服务器
$ python manage.py runserver $ python manage.py runserver 8089
在Windows通过debain的主机ip访问
$ python manage.py runserver 10.251.121.37:8989 $ python manage.py runserver 10.251.121.37:8989 $ python manage.py runserver 10.10.8.62:8989 $ python manage.py runserver 127.0.0.1:8989
执行django的测试文件:
$ python manage.py test polls
三、创建模型
确保你在与manage.py相同的目录下,并且键入以下命令来创建你的应用:
$ python manage.py startapp polls #创建了polls应用文件
1、编辑polls/models.py文件,并让它看起来像这样:
from django.db import models
class Question(models.Model): #自动分配id为主键 question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')
class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
2、再次编辑mysite/settings.py文件,并修改INSTALLED_APPS设置以包含字符串’polls’。
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', )
现在Django知道要包含polls应用。 让我们运行另外一个命令:
$ python manage.py makemigrations polls #$ python manage.py makemigrations
sqlmigrate命令接收迁移文件的名字并返回它们的SQL语句:
$ python manage.py sqlmigrate weibodata 0004
现在,再次运行migrate以在你的数据库中创建模型所对应的表:
$ python manage.py migrate
$ python manage.py runserver
备注:记住实现模型变更的三个步骤:
1、修改你的模型(在models.py文件中)。
2、运行 $ python manage.py runserver
$ python manage.py makemigrations //为这些修改创建迁移文件
Ps:sqlmigrate命令接收迁移文件的名字并返回它们的SQL语句:
$ python manage.py sqlmigrate polls 0001
3、运行
python manage.py migrate
将这些改变更新到数据库中。
四、玩转API
使用如下命令来调用Python shell:
$ python manage.py shell
探索这些数据库 API:
from polls.models import Question, Choice, mysitedata
from django.utils import timezone
Question.objects.all()
[]
q = Question(question_text=”What’s new?”, pub_date=timezone.now())
q.save()
或者:Question(question_text=”这但是是”, pub_date=timezone.now()).save()
mysitedata(mysite_text="测试", pub_date=timezone.now(),m_name="这", m_URL="www.baidu,com", o1_type=0,t1_color=1,fir_ss1="内部系统",sec_ss2="热门").save()
五、创建一个管理员用户
1、首先,我们需要创建一个能够登录管理站点的用户。 运行如下命令:
$ python manage.py createsuperuser
键入你想要使用的用户名,然后按下回车键:
Username: admin
然后提示你输入想要使用的邮件地址:
Email address: admin@example.com
最后一步是输入你的密码。 你将被要求输入你的密码两次,第二次输入是为了确认第一次的输入。
Password: ********** Password (again): ********* Superuser created successfully.
现在,打开一个浏览器访问你本地域名中的 “/admin/” —— 例如http://127.0.0.1:8000/admin/
2、我们需要告诉管理站点Question 对象要有一个管理界面。 要做这件事,需要打开polls/admin.py文件,把它编辑成这样:
from django.contrib import admin from .models import Question admin.site.register(Question)
添加关联对象
好了,我们已经有自己的Question管理界面。 但是一个Question有多个Choices,管理界面中并没有将选项显示出来。
有两种方法来解决这个问题。 第一种是像我们为Question做的一样,在管理站点中注册Choice。这简单:
在polls/admin.py文件中
from django.contrib import admin from .models import Choice, Question # ... admin.site.register(Choice)
但事实上,这是一种不高效的方式来添加Choice对象到系统中。在创建Question对象的同时可以直接添加一组Choice将会更好。让我们实现这个功能。
移除对Choice模型的register()调用。然后将Question的注册代码编辑为:
在polls/admin.py文件中
from django.contrib import admin from .models import Choice, Question class ChoiceInline(admin.StackedInline): model = Choice extra = 3
class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin)
六、编写你的第一个视图
让我们来编写第一个视图。 打开polls/views.py文件并将以下Python代码写入:
from django.http import HttpResponse
def index(request): return HttpResponse("Hello, world. You're at the polls index.")
为了能够调用这个视图,我们需要将这个视图映射到URL上 —— 利用一个URLconf。
为了在投票应用目录内部创建URLconf,需要创建一个urls.py文件。你的应用的目录现在看起来应该像这样:
polls/ __init__.py admin.py models.py tests.py urls.py views.py
在polls/urls.py文件中键入如下代码:
from django.conf.urls import url
from . import views
urlpatterns = [ url(r'^$', views.index, name='index'), ]
下一步,让主URLconf可以链接到polls.urls模块。在mysite/urls.py中插入一个include():
from django.conf.urls import include, url from django.contrib import admin
urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), ]
现在我们已经将一个index视图关联到URLconf中。在你的浏览器中浏览 http://localhost:8000/polls/ , 你会看到 “Hello, world. You’re at the polls index.”, 正如你在index 视图中定义的那样.
备注:编写更多的视图
现在让我们给polls/views.py添加一些更多的视图。这些视图和之前的略有不同,因为它们另带了一个参数:
def detail(request, question_id):
return HttpResponse(“You’re looking at question %s.” % question_id)
def results(request, question_id):
response = “You’re looking at the results of question %s.”
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse(“You’re voting on question %s.” % question_id)
通过下面的url() 调用将这些新的视图和polls.urls模块关联起来:
from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /polls/
url(r’^$’, views.index, name=’index’),
# ex: /polls/5/
url(r’^(?P
# ex: /polls/5/results/
url(r’^(?P
# ex: /polls/5/vote/
url(r’^(?P
]
备注:编写拥有实际功能的视图
1、快捷方式:render()
常见的习惯是载入一个模板、填充一个context 然后返回一个含有模板渲染结果的HttpResponse对象。Django为此提供一个快捷方式。
在polls/views.py文件中
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by(‘-pub_date’)[:5]
context = {‘latest_question_list’: latest_question_list}
return render(request, ‘polls/index.html’, context)
将以下的代码放入模板文件:在polls/templates/polls/index.html文件中
No polls are available.
2、快捷方式:get_object_or_404()
一种常见的习惯是使用get()并在对象不存在时引发Http404。Django为此提供一个快捷方式。
在polls/views.py文件中:
from django.shortcuts import get_object_or_404, render
from .models import Question # ... def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) 在polls/templates/polls/detail.html文件中: <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %}
{{ choice.choice_text }} {% endfor %} </ul>
七、移除模板中硬编码的URLs
还记得吗,当我们在polls/index.html模板中编写一个指向Question的链接时,链接中一部分是硬编码的:
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
这种硬编码、紧耦合的方法有一个问题,就是如果我们想在拥有许多模板文件的项目中修改URLs,那将会变得很有挑战性。 然而,因为你在polls.urls模块的url()函数中定义了name 参数,你可以通过使用{% url %}模板标签来移除对你的URL配置中定义的特定的URL的依赖:
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
它的工作原理是在polls.urls模块里查找指定的URL的定义。你可以看到名为‘detail’的URL的准确定义:
... # the 'name' value as called by the {% url %} template tag url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), ... 如果你想把polls应用中detail视图的URL改成其它样子比如 polls/specifics/12/,就可以不必在该模板(或者多个模板)中修改它,只需要修改 polls/urls.py: ... # added the word 'specifics' url(r'^specifics/(?P<question_id>[0-9]+)/$', views.detail, name='detail'), ...