django-语法备忘录

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 # Import the model classes we just wrote.
# 系统中还没有 polls 。
>>> Poll.objects.all()
[]
# 创建一个新 Poll 。
# 在默认配置文件中时区支持配置是启用的,
# 因此 Django 希望为 pub_date 字段获取一个 datetime with tzinfo 。 使用了 timezone.now()
# 而不是 datetime.datetime.now() 以便获取正确的值。
>>> from django.utils import timezone
>>> p = Poll(question="What's new?", pub_date=timezone.now())
# 保存对象到数据库中。 你必须显示调用 save() 方法。
>>> p.save()
# 现在对象拥有了一个ID 。 请注意这可能会显示 "1L" 而不是 "1", 取决于
# 你正在使用的数据库。 这没什么大不了的, 它只是意味着你的数据库后端
# 喜欢返回的整型数作为 Python 的长整型对象而已。
>>> p.id
1 #
通过 Python 属性访问数据库中的列。
>>> p.question
"What's new?"
>>> p.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
# 通过改为属性值来改变值, 然后调用 save() 方法。
>>> p.question = "What's up?"
>>> p.save()

models

import datetime
from django.utils import timezone
from django.db import models

# Create your models here.

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
    model = Choice
    extra = 3

class PollAdmin(admin.ModelAdmin):
    fields = ['question', 'pub_date']  # 排序
    inlines = [ChoiceInline]           # 关联外键
    list_display = ('question', 'pub_date') # admin列表页包含的字段,默认只包含question
    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):  # poll_id是urls中(?P<poll_id>\d+)匹配的参数
    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,))) # HttpResponseRedirect 防止用户重复提交,reverse()有助于避免在视图中硬编码 URL 的功能

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'), # (?P<poll_id>\d+)匹配poll_id这个参数
]

# url(regex, view, kwargs=None, name=None, prefix='')
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.assertContains(response, "No polls are available.") # 断言response是否与status_code和text内容相应。将html设为True会将text作为html处理。
self.assertJSONEqual(raw, expected_data, msg=None) # 断言Json片段raw和expected_data是否相当。


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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值