Django

gravatar

#制作特殊标签 app/templatetags
 
from django import template
 
import urllib, hashlib
 
register = template.Library()
 
def gravatar(email, size=80):
    gravatar_url = "http://www.gravatar.com/avatar.php?"
    gravatar_url += urllib.urlencode({
        'gravatar_id':hashlib.md5(email).hexdigest(),
        'size':str(size)})
    return """<img src="%s" alt="gravatar for %s" />""" % (gravatar_url, email)
 
register.simple_tag(gravatar)

修改数据库

python manage.py sqlall blog  #显示数据据命令
 
BEGIN;
CREATE TABLE "myblogapp_post" (
    "id" integer NOT NULL PRIMARY KEY,
    "author_id" integer NOT NULL REFERENCES "auth_user" ("id"),
    "title" varchar(200) NOT NULL,
    "slug" varchar(200) NOT NULL,
    "date_created" datetime NOT NULL,
    "date_modified" datetime NOT NULL,
    "tags" varchar(200) NOT NULL,
    "body" text NOT NULL,
    "body_html" text NOT NULL,
    "lc_count" integer NOT NULL
);
CREATE INDEX myblogapp_post_author_id ON "myblogapp_post" ("author_id");
CREATE INDEX myblogapp_post_slug ON "myblogapp_post" ("slug");
COMMIT;

手动添加

$ sqlite3 mydatabase.sqlite3
sqlite> ALTER TABLE myblogapp_post ADD COLUMN author_id integer REFERENCES auth_user (id);
sqlite> .exit

保留原数据,自动重建数据库

#django_evolution  需安装插件后./manage syncdb
./manage.py evolve --hint --execute
</cdoe>
 
===== django-paniation =====
<code python>
INSTALLED_APPS = (
    # ...
    'pagination',
)
 
MIDDLEWARE_CLASSES = (
    # ...
    'pagination.middleware.PaginationMiddleware',
)
 
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.request',
)
 
#view.py
from django.template import RequestContext
context_instance=RequestContext(request)  #add post_list
 
#index.html
{% load pagination_tags %}
{% autopaginate post_list 10 %}
{% paginate %}

生成随机日志

for x in range(10000):
   post = Post(title="Post %s%s" %(x,x) , pub_date=datetime(2010,3,6),body="POST 100%s" %(x),author=aa,slug="post-test%s" %(x),tags="post")
   post.save()
from django.db import models
 
    @models.permalink
 
    def get_absolute_url(self):
     return ('blog.views.post_detail', (), {    #blog.views.post_detail与url.py中引用文件及变量相同
        'year': self.pub_date.year,
             'month': self.pub_date.month,
        'day': self.pub_date.day,
        'slug': self.slug
        })

djang debug toolbar install

MIDDLEWARE_CLASSES = (
    'debug_toolbar.middleware.DebugToolbarMiddleware',  #add
)
 
INTERNAL_IPS = ('127.0.0.1',)  #add
 
INSTALLED_APPS = (
    'debug_toolbar',    #add
)
models.ForeignKey  #one to many
 
./manage.py reset blog  #重构数据库表,内容会丢失,reset后接应用程序名

Feeds设置

估计是自己水平问题找了几篇django关于Feeds的设置都不行,最后在一个国外的网站找到个解决办法,需要加强学习。

feeds.py

from django.contrib.syndication.feeds import Feed
from blog.core.models import Post
 
class PostFeed(Feed):
    '''Feed for latest 15 blog entries. '''
    Title = 'Django Blog'
    link  = 'http://172.30.24.24:8000/blog/list'
    description = 'Latest Blog Entries'
 
    item_author_name = 'Gavin'
    item_author_email = 'blog@yepn.net'
    item_author_link = 'http://blog.yepn.net'
 
    def items(self):
        return Post.objects.all()[:15]   #Post输出在models中定义已经为时间倒序
 
    def item_pubdate(self,item):
        return item.publish

urls.py

from django.conf.urls.defaults import *
from feeds import *   #feeds程序的路径需要特别注意
 
#Here you add a dictionary of feeds with a slug you want them to correspond to
 
site_feeds = {
        'posts':BlogFeed        #blog -->为feeds/posts的feed访问形式
}
 
urlpatterns = patterns('',
  #Lots of patterns omitted here
  (r'^feeds/(?P< url >.*)/$', 'django.contrib.syndication.views.feed',{'feed_dict':site_feeds}),
)

Learning Website Development with Django 读书笔记

django 用户
from django.contrib.auth.models import User
 
user = User.objects.get(username='用户名')
ERROR
 
<django.db.models.fields.related.ManyRelatedManager object at 0x01791B30> 等等一堆不知所谓的内容。
 
原因是模板中的{{object.categories}}是一个ManyToMany类型的域,是由多个categories对象组成,因此,将模板修改如下:
 
% for cate in object.categories.all %}
    {{ cate }}
{% endfor %}</div><br />
python manage.py sql APP    #查看生砀SQL语句

Django 1.0 Template Development

urls.py文中

from django.conf.urls.defaults import *
 
urlpatterns = patterns('',
    (r'detail/(?P<pid>\d+)/$','mycompany.press.views.detail'),
    (r'list/$', 'mycompany.press.views.press_list'),
    (r'$', 'django.views.generic.simple.redirect_to',
    {'url': '/press/list/'})
    )
django.views.generic.simple.redirect_to 跳转链接

Django Step by Step 学习笔记 Django 1.0.2版本

第(七)部分

修改表单之后需要重置数据库,同时数据会丢失

manage.py sqlreset address|sqlite3 data.db

django旧版可以使用 radio_admin=True 来表示在 admin 的管理界面中将使用 radio 按钮来处理

但新版不支持,所以没办法就去掉了这个,因为我一直找不到对应的功能。

向admin管理页面添加新站点
#more address/admin.py
 
from django.contrib import admin
from mysite.address.models import Address  #此处为mysite->站点名.address->应用程序名.models from Address->类名
 
admin.site.register(Address)
 
新增管理网站之后需要重启服务
 
#more address/models.py      #显示地址列表代码
#coding=utf-8                              #指定编码很重要
from django.db import models
 
# Create your models here.
class Address(models.Model):
    name = models.CharField('姓名',max_length=20,unique=True)
    gender = models.CharField('性别',choices=(('M','男'),('F','女')),max_length=1)
    telphone = models.CharField('电话',max_length=20)
    mobile = models.CharField('手机',max_length=11)
    def __unicode__(self):
        return self.name

创建address/urls.py文件

from django.conf.urls.defaults import *
from newtest.address.models import Address
 
info_dict = {
    'queryset': Address.objects.all(),
}
urlpatterns = patterns('',
    (r'^/?$', 'django.views.generic.list_detail.object_list', info_dict),
)
object_list函数特别说明,使用 object_list() 需要的模板文件名为: app_label/model_name_list.html ,这是缺省要查找的模板名。

第(六)部分

models.CharField 变量名改变

more wiki/models.py
from django.db import models
 
# Create your models here.
class Wiki(models.Model):
        pagename = models.CharField(max_length=20, unique=True) #maxlength变量变为max_length
        content = models.TextField()

Django 1.0开始自动转义超链

more templates/wiki/page.html
<h2>{{ pagename }}</h2>
{% autoescape off %} #禁用超级链代码
<p>{{ content }}</p>
{% endautoescape %}
<hr/>
<p>
<form method="POST" action="/wiki/{{ pagename }}/edit/">
<input type="submit" value="編集">
</form></p>
/var/lib/openshift/bccd8eac1968476490eaee9ced33c7bf/app-root/runtime/repo/php/data/pages/django.txt · 最后更改: 2012/09/07 09:21 (外部编辑)
到顶部
CC Attribution-Noncommercial-Share Alike 3.0 Unported
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0