Django study notes

Django official website: https://www.djangoproject.com/


Django object methods and example:
from django.http import HttpResponse
from django.template import Context, Template
from django.template.loader import get_template
from django.shortcuts import render_to_response
//return render_to_response('current_datetime.html', {'current_date': now})


1.Time zone settings:
File: settings.py
Parameter: TIME_ZONE = 'Etc/GMT-8'

2.Template: Method invocation behavior of the template
Parameter: silent_variable_failure=True(False)
In the object if silent_variable_failure=True, no exception is thrown and the value will be set to an empty string

3. Template: for loop counter
{% for item in todo_list %}
<p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}
forloop.counter //begin set to 1
forloop.counter0 //begin set to 0
forloop.revcounter //the cycle total number of remaining items, last cycle of this variable is set to 1
forloop.revcounter0 //similar to forloop.revcounter, last cycle of this variable is set to 0
forloop.first//is a boolean value in the first cycle is set to true
forloop.last//is a boolean value in the last cycle is set to true
forloop.parentloop //on a layer loop of current loop
{% for country in countries %}
<table>
{% for city in country.city_list %}
<tr>
<td>Country #{{ forloop.parentloop.counter }}</td>
<td>City #{{ forloop.counter }}</td> <td>{{ city }}</td>
</tr>
{% endfor %}
</table>
{% endfor %}

4.Template: locals()
username = name
return render_to_response('index.html', locals())
//locals() mothod can transfer all local variable,
//equivalent to render_to_response('index.html', {'username':name})

5.template: include
{% include "includes/nav.html" %}//TEMPLATE_DIRS/

6.template: extends
{% extends %} must ensure that the tag for the first
{{ block.super }} access to the content of the parent template
File: base.html //base template
<!DOCTYPE HTML PUBLIC "‐//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My helpful timestamp site</h1>
{% block content %}{% endblock %}
{% block footer %}
<hr> <p>Thanks for visiting my site.</p>
{% endblock %}
</body> </html>

File: sub.html
{% extends "base.html" %}
{% block title %}Future time{% endblock %}
{% block content %}
<p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p>
{% endblock %}



ifequal/ifnotequal

{% ifequal %} 标签比较两个值,当他们相同时,显示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。

下面的例子比较两个模板变量 user 和 currentuser :

{% ifequal user currentuser %}
    <h1>Welcome!</h1>
{% endifequal %}

参数可以是硬编码的字符串,随便用单引号或这双引号引起来,所以下列代码都是正确的:

{% ifequal section 'sitenews' %}
    <h1>Site News</h1>
{% endifequal %}

 

{% ifequal section "community" %}
    <h1>Community</h1>
{% endifequal %}

{% ifequal section 'sitenews' %}
    <h1>Site News</h1>
{% else %}
    <h1>No News Here</h1>
{% endifequal %}

注释

象HTML和其他的语言例如python一样,Django模板系统也允许注释。 注释使用 {# #}

{# This is a comment #}



这个例子使用了神奇的 Python 内部变量__file__,该变量被自动设置为代码所在的 Python 模块文件名。

TEMPLATE_DIRS = (

os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),

)






7.Model
edit settings.py //configuration parameters under the databases
python manage.py shell
>>> from django.db import connection
>>> cursor = connection.cursor()//test database connection

python manage.py startapp books //create application books
edit books/models.py //add the following code
-------------------------------------------------------------------------------------------
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
-------------------------------------------------------------------------------------------
edit settings.py
//comment out all the INSTALLED_APPS and MIDDLEWARE_CLASSES

adding in INSTALLED_APPS:
'books', //application name

python manage.py validate //Verify the model validity
python manage.py sqlall books //generate the creat table statement

//Confirm sql correct execution:
python manage.py syncdb
-------------------------------------------------------------------------------------------
insert data into the database & application name: book
from books.models import Publisher//Publisher - from table name book_publisher
p1 = Publisher(name='Apress', address='2855 Telegraph Avenue', ....
//Equivalent to - insert into book_publisher (`name`, `address` ...)values('Apress', '2855 Telegraph Avenue'', ...)
p1.save() //execute
Publisher.objects.all() //Equivalent to select * from book_publisher
Publisher.objects.filter(country="U.S.A.", state_province="CA")
// select * from appname_tablename where country='U.S.A' AND state_province = 'CA'
Publisher.objects.filter(name__contains="press") //double underline equal to "like"
//select * from book_publisher name LIKE "%press%"

Publisher.objects.get(name="Apress") //get mothed equal to select Apress from table
Publisher.objects.order_by("name")//select * FROM books_publisher ORDER BY name;
Publisher.objects.order_by("state_province", "address")//select *from books_Publisher order by state_province and order by address

**class Meta:**
**ordering = ['name']** //default order by name

Publisher.objects.filter(country="U.S.A.").order_by("‐name")
//select * FROM books_publisher WHERE country = 'U.S.A' ORDER BY name DESC;

Publisher.objects.order_by('name')[0]
//select * FROM books_publisher ORDER BY name LIMIT 1;
Publisher.objects.order_by('name')[0:2]
//select * FROM books_publisher ORDER BY name OFFSET 0 LIMIT 2;

Publisher.objects.filter(id=52).update(name='Apress Publishing')
//UPDATE books_publisher SET name = 'Apress Publishing' WHERE id = 52;
Publisher.objects.all().update(country='USA')
//update books_publisher set country='USA'

Publisher.objects.filter(country='USA').delete()
//delete books_publisher where country='USA'

 

o=Publisher.objects.all()     //select * fromPublisher

                              //query function  o.values or o.values_list

o=Publisher.objects.filter(name='xxx')   //select * fromPublisher where name = 'xxx'

                                         //query function  o.values or o.values_list

 

获取单个对象

o=Publisher.objects.get(name="Apress Publishing")   //select * from Publisher where name = 'xxx'

                                                    // query function o.字段名, 如果结果是多个对象,会导致抛出异常:

 

 

 

 

 

 

引入其他目录models

settings.py  (INSTALLED_APPS)

     mysite.application.models.post         //post.py内容 class xxx

                                                               //equal create table post_xxx

 

python manage.py sqlall post

 

 




6.Django admin
edit settings.py //add following code for INSTALLED_APPS
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
and add following code for MIDDLEWARE_CLASSES
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
-------------------------------------------------------------------------------------------
python manage.py syncdb //generate management interface of the database table
python manage.py createsuperuser //create admin user

edit url.py //uncommenting this statement
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),


7.form
def current_url_view_good(request):
return HttpResponse("Welcome to the page at %s" % request.path)

HttpRequest对象包含当前请求URL的一些信息:


属性/方法说明举例

属性/方法说明举例
request.path除域名以外的请求路径,以正斜杠开头"/hello/"
request.get_host()主机名(比如,通常所说的域名)"127.0.0.1:8000" or "www.example.com"
request.get_full_path()请求路径,可能包含查询字符串"/hello/?print=true"
request.is_secure()如果通过HTTPS访问,则此方法返回True, 否则返回FalseTrue 或者 False
request.META['HTTP_REFERER']进站前链接网页,如果有的话。 (请注意,它是REFERRER的笔误。) 
request.META['HTTP_USER_AGENT']用户浏览器的user-agent字符串,如果有的话"Mozilla/5.0 (X11; U; Linux i686; fr‐FR; rv:1.8.1.17) Gecko/20080829 Firefox/2.0.0.17"
request.META['REMOTE_ADDR']客户端IP"12.345.67.89" 。(如果申请是经过代理服务器的话,那么它可能是以逗号分
割的多个IP地址,如:"12.345.67.89,23.456.78.90" 。)
request.metod()td>传递方式(POST or GET)if request.method == 'POST'




8. advance view and url setting

from django.conf.urls.defaults import *


urlpatterns = patterns('mysite.views',


(r'^hello/$', 'hello'), //mysite.views.hello


(r'^time/$', 'current_datetime'),


(r'^time/plus/(\d{1,2})/$', 'hours_ahead'),


)


9.advance templates


This will be escaped: {{ data }}
This will not be escaped: {{ data|safe }}


{% autoescape off %}
This will not be auto‐escaped: {{ data }}.


Nor this: {{ other_data }}
{% autoescape on %}
Auto‐escaping applies again: {{ name }}
{% endautoescape %}
{% endautoescape %}


//autoescape 标签有两个参数on和off 有时,你可能想阻止一部分自动转意,对另一部分自动转意


custom template filter


register = template.Library()
@register.filter(name='cut')
def cut(value, arg):
return value.replace(arg, '')
----------
{{ somevariable|cut:" " }}

10.advance data model
>>> from books.models import Book
>>> b = Book.objects.get(id=50)
>>> b.title
u'The Django Book' //access to the database object data

django执行原始SQL查询
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
SELECT DISTINCT first_name FROM people_person
WHERE last_name = %s""", ['Lennon']
""")
row = cursor.fetchone()
print row //['John']


view judgment 404

from django.http import Http404


from django.template import TemplateDoesNotExist


from django.views.generic.simple import direct_to_template


def about_pages(request, page):


try:


return direct_to_template(request, template="about/%s.html" % page)


except TemplateDoesNotExist:


raise Http404()

django cookie settings

response = HttpResponse("login accessi %s" % request.COOKIES['user'])
response.set_cookie("user", request.GET["user"])
response.set_cookie("passwd", request.POST['passwd'])
return response
django cookie

设置测试Cookies
就像前面提到的,你不能指望所有的浏览器都可以接受cookie。 因此,为了使用方便,Django提供了一个简单的方法来测试用户的浏览器是否接受cookie。 你只需在视图(view)中调用 request.session.set_test_cookie(),并在后续的视图(view)、而不是当前的视图(view)中检查 request.session.test_cookie_worked() 。
虽然把 set_test_cookie() 和 test_cookie_worked() 分开的做法看起来有些笨拙,但由于cookie的工作方
式,这无可避免。 当设置一个cookie时候,只能等浏览器下次访问的时候,你才能知道浏览器是否接受
cookie。
检查cookie是否可以正常工作后,你得自己用 delete_test_cookie() 来清除它,这是个好习惯。 在你证实了
测试cookie已工作了之后这样操作。
这是个典型例子:
def login(request):
# If we submitted the form...
if request.method == 'POST':
# Check that the test cookie worked (we set it below):
if request.session.test_cookie_worked():
# The test cookie worked, so delete it.
request.session.delete_test_cookie()
# In practice, we'd need some logic to check username/password
# here, but since this is an example...
return HttpResponse("You're logged in.")
# The test cookie failed, so display an error message. If this
# were a real site, we'd want to display a friendlier message.
else:
return HttpResponse("Please enable cookies and try again.")
# If we didn't post, send the test cookie along with the login form.
request.session.set_test_cookie()
return render_to_response('foo/login_form.html')




Django session settings
打开 Sessions功能
Sessions 功能是通过一个中间件(参见第17章)和一个模型(model)来实现的。 要打开sessions功能,需要以下
几步操作:
1. 编辑 MIDDLEWARE_CLASSES 配置,确保 MIDDLEWARE_CLASSES 中包含
'django.contrib.sessions.middleware.SessionMiddleware'。
2. 确认 INSTALLED_APPS 中有 'django.contrib.sessions' (如果你是刚打开这个应用,别忘了运行manage.py syncdb )
to use the session view
# Set a session value:
request.session["fav_color"] = "blue"
# Get a session value ‐‐ this could be called in a different view,
# or many requests later (or both):
fav_color = request.session["fav_color"]
# Clear an item from the session:
del request.session["fav_color"]
# Check if the session has a given key:
if "fav_color" in request.session:

18. Integration with existing databases and applications
django-admin.py startproject mysite
edit mysite/settings.py //configuration DATABASE_NAME , DATABASE_ENGINE , DATABASE_USER , DATABASE_PASSWORD , DATABASE_HOST and DATABASE_PORT
python mysite/manage.py startapp myapp
python mysite/manage.py inspectdb //This will check the table in the DATABASE_NAME database and print out for each tables generated model classes
python mysite/manage.py inspectdb >> mysite/myapp/models.py //saved to models.py

19. Internationalization
from django.utils.translation import ugettext as _
def my_view(request):
output = _("Welcome to my site.")
return HttpResponse(output) //output u'string'

def my_view(request, m, d):
output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
return HttpResponse(output)//use placeholder

from django.utils.translation import ugettext_lazy
//django.utils.translation.gettext_lazy() 函数,使得其中的值只有在访问时才会被翻译,而不是在 gettext_lazy() 被调用时翻译。


<title>{% trans "This is the title." %}</title>
{% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}

{% blocktrans with book|title as book_t and author|title as author_t %}
This is {{ book_t }} by {{ author_t }}
{% endblocktrans %}
//









django doc official website:      https://docs.djangoproject.com/en/1.4/ 









143
1.7
to be continued .......
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值