一、使用Django自带的后端管理平台

1、后台创建管理员

python manage.py createsuperuser
Email address: admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.

2、打开后台页面

http://127.0.0.1:8000/admin/

输入刚才的用户名及密码登陆:

此时还看不到我们刚才创建的数据表

那我们打开polls/admin.py文件,把我们所创建的数据表配置进去后台,可以通过修改models.py / admin.py代码来设置多种显示格式,其中一种如下:

from django.contrib import admin
from polls.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文件夹下方创建一个名叫templates的目录,再修改如下配置文件,把目录添加到系统路径

mysite/settings.py
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

各种template如下:
templates/polls/index.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label>
<br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
templates/polls/results.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
 

三、创建视图

polls/views.py

from django.shortcuts import render,get_object_or_404
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone from polls.models import Choice, Question # Create your views here. class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list' def get_queryset(self):
"""Return the last five published question"""
return Question.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5] class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
def get_queryset(self):
return Question.objects.filter(pub_date__lte=timezone.now()) class ResultsView(generic.DetailView):
model=Question
template_name = 'polls/results.html' def vote(request, question_id):
p=get_object_or_404(Question,pk=question_id)
try:
selected_choice=p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request,'polls/detail.html',{
'question':p,
'error_message':"You didn't select a choice",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results',args=(p.id,)))

mysite/urls.py   总的url配置

from django.conf.urls import patterns, include, url
from django.contrib import admin urlpatterns = patterns('',
url(r'^polls/', include('polls.urls',namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
)

polls/urls.py  子url配置

from django.conf.urls import patterns,url
from polls import views urlpatterns=patterns('',
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>\d+)/$',views.DetailView.as_view(),name='detail'),
url(r'^(?P<pk>\d+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>\d+)/vote/$',views.vote,name='vote'),
)

四、最终Models如下:

polls/models.py

import datetime
from django.db import models
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):
now = timezone.now()
return now >= self.pub_date >= now - datetime.timedelta(days=1)
was_published_recently.admin_order_field='pub_date'
was_published_recently.bollean = True
was_published_recently.short_description='Published recently?' 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

五、自定义样式/静态文件位置配置,在polls文件夹下面创建static文件夹

静态文件如:polls/static/polls/style.css

mysite/settings.py 文件中应有下面的默认配置,如果没有,手动添加

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/'
#STATIC_URL = [os.path.join(BASE_DIR,'static')]

  

最新文章

  1. Spring_跨项目读取properties文件
  2. SWFUpload多图上传、C#后端跨域传文件带参数
  3. 网页中tab标签切换分别用jquery和javascript源码实现
  4. 设置statusBarStyle
  5. System.Security.SecurityException The type initializer for &#39;System.Data.Entity.Internal.AppConfig&#39; threw an exception
  6. html5 base64基础
  7. 一个PHP加密脚本,达到一定免杀效果
  8. [译] ASP.NET 生命周期 – ASP.NET 应用生命周期(一)
  9. html》meta标签笔记
  10. 针对不同手机系统的LBS地图定位解决方案
  11. 网站静态化处理—web前端优化—中(12)
  12. Java 中基本类型和字符串之间的转换
  13. NancyFX 第十章 身份验证
  14. Yarn篇--搭建yarn集群
  15. unity项目build成webgl时选择生成目录(解决方法)
  16. Scrapy创建项目问题
  17. C++中的stack类、QT中的QStack类
  18. 关于vue-cli创建项目(小白)
  19. git checkout -b mybranch和git checkout mybranch
  20. 20155326 2016-2017-2 《Java程序设计》第九周学习总结

热门文章

  1. centos上如何安装redis?|centos傻瓜式安装redis教程
  2. webmagic 增量爬取
  3. jQuery动态增删改查表格信息,可左键/右键提示
  4. __index
  5. HashMap Hasptable的区别
  6. block要掌握的东西
  7. eclipse version
  8. 如何快速上手使用STM32库函数
  9. 《征服 C 指针》摘录4:函数 与 指针
  10. Linux学习之一--VI编辑器的基本使用