Writing your first Django app, part 1
介绍创建项目和app,创建表,更新表,运行,model编写
requriments : Django 1.8 and Python 2.7
创建项目django-admin startproject mysite
.
├── manage.py 命令行呢功能
└── mysite 项目的python包
├── __init__.py 告诉python这个目录是个python包
├── settings.py 配置文件
├── urls.py 支持的url
└── wsgi.py 兼容WSGI的web服务的进入点
更改数据库在settings文件中更改DATABASES
建表python manage.py migrate
创建app python manage.py startapp polls
python manage.py sqlmigrate polls 000
sqlmigrate命令实际上并不在数据库上运行迁移,它只是打印到屏幕上,是用于检查Django要做什么。
如果更改了model,即需要更新表
python manage.py makemigrations : create migrations for those changes
python manage.py migrate :apply those changes to the database.
python manage.py shell
manage.py 设置了 DJANGO_SETTINGS_MODULE 环境变量,which gives Django the Python import path to your mysite/settings.py file.
# mysite/polls/models.py from django.db import models import datetime from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
Writing your first Django app, part 2
介绍了添加超级用户,自定义管理界面,变更管理界面的外观
Creating an admin user : python manage.py createsuperuser
# mysite/polls/admin.py from django.contrib import admin from .models import Choice,Question # Register your models here. class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): #Customize the admin change list 自定义管理界面中的变更列表 list_display = ('question_text','pub_date','was_published_recently') list_filter = ['pub_date'] search_fields = ['question_text'] #Customize the admin form 自定义管理表单 #fields = ['pub_date','question_text'] fieldsets = [ (None,{'fields':['question_text']}), ('Date information',{'fields':['pub_date'],'classes':['collapse']}), ] inlines = [ChoiceInline] #Make the poll app modifiable in the admin 让poll应用在管理站点中可编辑 admin.site.register(Question,QuestionAdmin) #Adding related objects 添加关联对象 admin.site.register(Choice)
自定义管理站点的外观
将修改主页上的 Django Adminnistration 改为 Polls Administration
在setting.py中将 TEMPLATES的DIRS改为 [os.path.join(BASE_DIR, 'templates')]
先找到配置文件位置,运行如下
$ python -c " import sys sys.path = sys.path[1:] import django print(django.__path__)"
得到结果 ['/usr/lib64/python2.7/site-packages/django']
在上面的目录下找到 contrib/admin/templates/admin 下 base_site.html 拷贝到工程目录下新建 templates/admin/下 将{{ site_header|default:_('Django administration') }}替换为Polls Administration
Writing your first Django app, part 3
介绍模板template,url和view
#mysite/mysite/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), #带命名空间的URL名字 url(r'^polls/',include("polls.urls",namespace="polls")), ]
# mysite/polls/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^(?P<question_id>[0-9]+)/$',views.detail,name='detail'), url(r'^(?P<question_id>[0-9]+)/results/$',views.results,name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'), ]
# mysite/polls/views.py from django.shortcuts import render from django.http import HttpResponse from .models import Question #from django.template import loader # Create your views here. def index(request): print request latest_question_list = Question.objects.order_by('-pub_date')[:5] #template = loader.get_template('polls/index.html') #output = ','.join([p.question_text for p in latest_question_list]) context = { 'latest_question_list': latest_question_list, } #return HttpResponse(output) #return HttpResponse(template.render(context,request)) #快捷方式:render() return render(request,'polls/index.html',context) def detail(request,question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exit") #return HttpResponse("You`re looking at question %s." % question_id return render(request,'polls/detail.html',{'question':question}) 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)
<!--mysite/polls/templates/polls/index.html--> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <!--移除模板中硬编码的URLs,带命名空间的URL名字 -->
<li><a href="{% url 'polls:detail' question.id}">{{question.question_text}}</a></li>
{% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
<!--mysite/polls/templates/polls/detail.html--> <h1>{{question.question_text}}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %} </ul>
Writing your first Django app, part 4