diango命令
python manage.py makemigrations 生成migration文件
python manage.py migrate 对数据库进行操作
python manage.py validate – 检查在构建你的模型时是否有错误
python manage.py sqlcustom polls – 输出为应用定义的任何 custom SQL statements (例如表或约束的修改 )
python manage.py sqlclear polls – 根据存在于你的数据库中的表 (如果有的话),为应用输出必要的 DROP TABLE
python manage.py sqlindexes polls – 为应用输出 CREATE INDEX 语句
python manage.py sqlall polls – 输出所有 SQL 语句:sql, sqlcustom, 和 sqlindexes
django-admin.py startproject mysite
创建django工程
python manage.py startapp polls
创建django应用
python manage.py shell
进入django交互式shell
python manage.py createsuperuser
创建超级用户
settings
1. 数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
ENGINE – 'django.db.backends.postgresql_psycopg2', 'django.db.backends.mysql','django.db.backends.sqlite3', 'django.db.backends.oracle'
NAME – 数据库名
USER – 你的数据库用户名 ( SQLite 下不需要)
PASSWORD – 你的数据库密码 ( SQLite 下不需要)
HOST – 你的数据库主机地址。 如果和你的数据库服务器是同一台物理机器, 请将此处保留为空 (或者设置为 127.0.0.1) ( SQLite 下不需要)
2. 应用
它保存了当前 Django 实例已激活的所有Django 应用
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
django.contrib.auth – 身份验证系统
django.contrib.contenttypes – 内容类型框架
django.contrib.sessions – session 框架
django.contrib.sites – 网站管理框架
django.contrib.messages – 消息框架
django.contrib.staticfiles – 静态文件管理框架
3. 时区
TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'
django shell交互模式使用
>>> from polls.models import Poll, Choice
>>> Poll.objects.all()
[]
>>> from django.utils import timezone
>>> p = Poll(question="What's new?", pub_date=timezone.now())
>>> p.save()
>>> p.id
1
通过 Python 属性访问数据库中的列。
>>> p.question
"What's new?"
>>> p.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
>>> p.question = "What's up?"
>>> p.save()
models
import datetime
from django.utils import timezone
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
admin
在admin中启用指定应用:在app下的admin.py中加入以下
from django.contrib import admin
from polls.models import Poll, Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fields = ['question', 'pub_date']
inlines = [ChoiceInline]
list_display = ('question', 'pub_date')
list_filter = ['pub_date']
search_fields = ['question']
date_hierarchy = 'pub_date'
admin.site.register(Poll, PollAdmin)
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from polls.models import Poll
from django.http import Http404
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
def detail(request, poll_id):
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
return render(request, 'polls/detail.html', {'poll': poll})
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
context = {'latest_poll_list': latest_poll_list}
return render(request, 'polls/index.html', context)
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'poll': 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,)))
urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
url(r'^$', views.index, name='index'),
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
]
view - 指定的视图,如果使用简单的正则捕获, 将按顺序位置传参数;如果按命名的正则捕获, 将按关键字传参数值
kwargs - 任意关键字参数可传一个字典至目标视图
name - 命名你的 URL,让你在 Django 的其他地方明确地引用它
模板
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.Loader', # Django会在每个INSTALLED_APPS 的 “templates” 子目录下查找模板
)
TEMPLATE_DIRS = (
)
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li> # 避免硬编码url,'detail'即urls.py中的name='detail',poll.id是url的参数.polls:detail需要在root URLconf中配置url(r'^polls/', include('polls.urls', namespace="polls")
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
# 模板系统使用了“变量.属性”的语法访问变量的属性值。 例如 {{ poll.question }}
# 在 {% for %} 循环中有方法调用: poll.choice_set.all 就是 Python 代码 poll.choice_set.all(),它将返回一组可迭代的 Choice 对象, 可以用在 {% for %} 标签中
<h1>{{ poll.question }}</h1>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'polls:vote' poll.id %}" method="post"> # 将 form 的 action 设置为 {% url 'polls:vote' poll.id %}
{% csrf_token %} # 防止跨站点请求伪造,所有的 POST form 针对内部的 URLs 时都应该使用 {% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> # 每个单选按钮的 value 是投票选项对应的 ID 。 每个单选按钮的 name 都是 “choice” 。 这意味着, 当有人选择了一个单选按钮并提交了表单, 将会发送 的 POST 数据是 choice=3
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> # forloop.counter 表示 for 标签在循环中已经循环过的次数
{% endfor %}
<input type="submit" value="Vote" />
</form>
test
在app中的test.py中写test
每个模型或视图具有一个单独的TestClass
为你想测试的每一种情况建立一个单独的测试方法
测试方法的名字可以描述它们的功能
python manage.py test:执行所有的测试用例
python manage.py test app_name, 执行该app的所有测试用例
python manage.py test app_name.case_name: 执行指定的测试用例
常用的断言函数
self.assertEqual(response.status_code, 200)
self.assertQuerysetEqual(response.context['latest_poll_list'], [])
self.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)
self.assertJSONEqual(raw, expected_data, msg=None)
import datetime
from django.utils import timezone
from django.test import TestCase
from .models import Poll
class PollMethodTests(TestCase):
def test_was_published_recently_with_future_Poll(self):
time = timezone.now() + datetime.timedelta(days=30)
future_Poll = Poll(pub_date=time)
self.assertEqual(future_Poll.was_published_recently(), True)
def test_was_published_recently_with_future_Poll_2(self):
time = timezone.now() + datetime.timedelta(days=30)
future_Poll = Poll(pub_date=time)
self.assertEqual(future_Poll.was_published_recently(), False)
静态文件
settings
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder" # 它在每个INSTALLED_APPS下查找“static”子目录
)
app下创建static目录及css文件
polls/static/polls/style.css
polls/templates/polls/index.html的顶端添加如下内容
{% load staticfiles %} # {% load staticfiles %} 从staticfiles模板库加载 {% static %} 模板标签。 {% static %} 模板标签会生成静态文件的绝对URL
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
背景图片
app下创建images目录
polls/static/polls/images/background.jpg
图片引用
body {
background: white url("images/background.jpg") no-repeat right bottom;
}