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 ...
随机推荐
- 使用.NET实现断点续传
http://www.cnblogs.com/goody9807/archive/2007/06/05/772501.html 断点续传的原理在了解HTTP断点续传的原理之前,先来说说HTTP协议,H ...
- 有米实习-用到的shell脚本和Python脚本记录
Shell:LOG_DATE=`date -d "1 day ago" +%Y-%m-%d` #以指定格式设置一天前的年份月份日期 aws s3 ls $LAST5_BASE_PA ...
- 2015.4.19 为什么footer下a的索引值那么大
1.问题demo:为什么footer下a的索引值那么大,index不是查找兄弟级别的元素么?而且还限定了范围在footer下的a的情况下. 解决方法:alert( $("#footer a& ...
- Qt、VTK配置常见问题
QVTKWidget undefined reference to 问题,一定要在pro文件中添加库 libvtkGUISupportQt-6.3. 2. CMAKE_MAKE_PROGRAM ...
- mac 上的 python
1.mac 上的 python 自己感觉很乱 1.额外安装的 自带的 python27-apple /System/Library/Frameworks/Python.framework/Versio ...
- 写JSP文件遇到的一个问题
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...
- 引用项目外dll时不显示注释的解决方案
在引用项目外的dll时,显示类库中的注释可按以下步骤: 方法或变量用summary添加注释,如: /// <summary>发送post请求 /// < ...
- Git命令回顾
团队从Eclipse迁移到Android Studio之后,也从SVN迁移到Git了. 一直忙于需求迭代无暇做迁移,现在才开始做,相见恨晚,好东西,高大上,词穷. 回顾和记录一下git的一些基本操作. ...
- ASP.NET获取客户端的相关信息
/// <summary> /// 获取远程浏览器端 IP 地址 /// </summary> /// <returns> ...
- Win10环境下安装Vmware+Ubuntu14 注意点
下载相关软件正常安装完成后可能会碰到以下两个问题,这里备注一下,备用 1.Ubuntu的root密码设置 2.Vmware网络连接设成桥接之后,Win10可以ping通Ubuntu,但Ubuntu无法 ...
