Django学习笔记之二
一、使用Django自带的后端管理平台
1、后台创建管理员
python manage.py createsuperuser
Email address: admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.
2、打开后台页面

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

此时还看不到我们刚才创建的数据表
那我们打开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的目录,再修改如下配置文件,把目录添加到系统路径
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')]
Django学习笔记之二的更多相关文章
- Django学习笔记(二):使用Template让HTML、CSS参与网页建立
Django学习笔记(二):使用Template让HTML.CSS参与网页建立 通过本文章实现: 了解Django中Template的使用 让HTML.CSS等参与网页建立 利用静态文件应用网页样式 ...
- Django 学习笔记(二)
Django 第一个 Hello World 项目 经过上一篇的安装,我们已经拥有了Django 框架 1.选择项目默认存放的地址 默认地址是C:\Users\Lee,也就是进入cmd控制台的地址,创 ...
- Django 学习笔记(二) --- HTML 模版
人生苦短 ~ Tips:仅适用于 Python 3+(反正差别不大,py2 改改也能用).因为据 Python 之父 Guido van Rossum 说会在 2020 年停止对 Python 2 的 ...
- Django学习笔记(二)视图函数
一.url映射 1.为什么回去urls.py文件中找映射? 在‘settings.py’文件中配置了‘ROOT_URLCONF’为‘urls.py’.所有的django回去urls.py中寻找. 2. ...
- django学习笔记(二)
上节内容回顾: 1.Django请求生命周期 -> URL对应关系(匹配) -> 视图函数 -> 返回用户字符串 -> URL对应关系(匹配) -> 视图函数 -> ...
- python Django 学习笔记(二)—— 一个简单的网页
1,创建一个django项目 使用django-admin.py startproject MyDjangoSite 参考这里 2,建立视图 from django.http import HttpR ...
- Django 学习笔记之二 基本命令
1.新建一个 django project 在Django安装路径下找到django-admin.py文件,我的路径是在C:\Python27\Lib\site-packages\Django-1.1 ...
- Django学习笔记(二)——django数据库的使用
1.模型——SQLite3数据库使用 使用django的数据库必须创建一个app python manage.py startapp check 创建app 此时manage.py的目录下会多一个c ...
- python之Django学习笔记(二)---Django从工程创建、app创建到表建模在页面的显示
创建工程: 在命令行中切换目录至需要创建工程的目录,然后在命令行中输入如下命令创建djangoTestPro工程 D:\PycharmProjects\untitled\MyTestProject&g ...
随机推荐
- 【原】理解javascript中的闭包
闭包在javascript来说是比较重要的概念,平时工作中也是用的比较多的一项技术.下来对其进行一个小小的总结 什么是闭包? 官方说法: 闭包是指有权访问另一个函数作用域中的变量的函数.创建闭包的常见 ...
- Windows操作系统待整理
12. 2001年10月25日Windows XP发布,Windows XP是基于Windows 2000代码的产品,同时拥有一个新的用户图形界面(叫做月神Luna),它包括了一些细微的修改.集成了防 ...
- Robots.txt - 禁止爬虫(转)
Robots.txt - 禁止爬虫 robots.txt用于禁止网络爬虫访问网站指定目录.robots.txt的格式采用面向行的语法:空行.注释行(以#打头).规则行.规则行的格式为:Field: v ...
- Activity初接触
Activity中TextView的文字显示Hello Android: 1.直接显示:<TextView android:text="Hello Android" /> ...
- MySql 外键约束 之CASCADE、SET NULL、RESTRICT、NO ACTION分析和作用
MySQL有两种常用的引擎类型:MyISAM和InnoDB.目前只有InnoDB引擎类型支持外键约束.InnoDB中外键约束定义的语法如下: ALTER TABLE tbl_name ADD [CON ...
- hadoop源码编译——2.5.0版本
强迫症必治: WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using b ...
- MySQL数据类型 int(M) 表示什么意思?详解mysql int类型的长度值问题
MySQL 数据类型中的 integer types 有点奇怪.你可能会见到诸如:int(3).int(4).int(8) 之类的 int 数据类型.刚接触 MySQL 的时候,我还以为 int(3) ...
- Shell入门教程:Shell的基本结构
shell程序的基本组成结构 shell结构大体是由设定变量.内置命令.shell的语法结构.函数组成. 使用实例说明:test.sh #!/bin/bash #说明使用/bin/bash作为这个脚本 ...
- Daily Scrum Meeting ——TenthDay
一.Daily Scrum Meeting照片 二.Burndown Chart 新增了几个issues 三.项目进展 1.完成了登录界面与管理员和发布者界面的整合. 2.活动发布者界面的完成 四.问 ...
- MFC在关闭第二个窗口时关闭主对话框
AfxGetApp()->m_pMainWnd->SendMessage(WM_CLOSE);//关闭主对话框
