用django框架做自己的blog

说明:我的系统环境是ubuntu 14.10版本的,整理这篇博客,主要是自己记性太不好了,老忘东西,教训一下自己。哈哈

参考文章

createing blog

1,part-1-creating-blog

2,part-2-creating-blog

3,part-3-creating-blog

django framework application

django framework

安装django及博客相关包

apt-get install python-django -y    #django version 1.7
pip install markdown pygments django-pagedown

create project

mkdir /var/www/django_project    #放用django框架开发的各类应用项目

cat  create_django_object.sh    # 创建项目及应用脚本

#!/bin/bash
dir=/var/www/django_project

cd $dir
django-admin.py startproject $1
cd $dir/$1
python manage.py startapp $2

#使用方法如下,传两个参数: 项目名称  应用名称
./create_django_object.sh mydjblog blog

配置项目wqkblog setting.py 如下:

# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #'south',
    'linaro_django_pagination',  #分页用
    'blog',
    'pagedown',
)
# 处理模板的功能
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    "django.core.context_processors.request"
)

# 连接数据库
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# 设置语言
LANGUAGE_CODE = 'zh-cn'
# 时区
TIME_ZONE = 'Asia/Shanghai'

静态文件及模板目录配置

# 静态文件目录
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

# 模版文件目录
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, "templates"),
)   
# 设置首页显的博客数量
PAGINATION_DEFAULT_PAGINATION = 3
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

create the models 给自己的应用创建models

说明:以python面向对象的思想将数据库表创建为类,类内部变量为字段名
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

class Category(models.Model):
    name = models.CharField(u'文章分类', max_length=64)

    class Meta:
        ordering = ['-id']

    def __unicode__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        return ('category', (), {'pk': self.pk})

class Post(models.Model):
    title = models.CharField(u"标题", max_length=128)
    author = models.ForeignKey(User)
    po_type = models.ForeignKey(Category, verbose_name=u'文章分类', blank=True, null=True)
    #content = models.TextField(u'Content (Markdown)')
    content = models.TextField(u'Content (Markdown)')
    pub_data = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-id"]

    def __unicode__(self):
        return self.title

    @models.permalink
    def get_absolute_url(self):
        return ('post', (), {'pk': self.pk})

create blog models to django admin

from django.contrib import admin
from django import forms
from pagedown.widgets import AdminPagedownWidget
from models import Post, Category

class CategoryAdmin(admin.ModelAdmin):
    #prepopulated_fields = {'slug':('name',)}
    list_display = ('name',)
    search_fields = ('name',)

class PostFrom(forms.ModelForm):
    class Meta:
        model = Post
        widgets = {
            'content':AdminPagedownWidget(),
        }


class PostAdmin(admin.ModelAdmin):
    form = PostFrom
    #prepopulated_fields = {'slug':('title',)}
    list_display = ('title','author','po_type','content','pub_data',)
    search_fields = ('title','content',)
    fieldsets = (
        (
            None,
            {
                'fields': ('title', 'author', 'po_type', 'content',)
            }
        ),

    )

admin.site.register(Post,PostAdmin)
admin.site.register(Category,CategoryAdmin)

创建数据库表结构

python manage.py syncdb
此过程中会提示输入管理员的用户名及密码,我这里全是root

启动django web服务

python manage.py runserver 0.0.0.0:9000

admin 后台登录添加数据

127.0.0.1:9000/admin

url与views配置编写为并template传值

setings.py同级主url配置
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
                       url(r'^', include('blog.urls')),
                       url(r'^admin/', include(admin.site.urls)),
)

blog 应用url配置
from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
                       url(r"^$", "blog.views.index", name="index"),
                       url(r"^post/(?P<pk>\d+)/$", "blog.views.post", name="post"),
                       url(r'^(?P<id>\d+)/$', 'blog.views.detail', name='detail'),
                       url(r"^category/(?P<pk>\d+)/$", "blog.views.category", name="category"),
                       url(r'^tag(?P<tag>\w+)/$', 'blog.views.search_tag', name = 'search_tag'),
                       url(r'^search/$','blog.views.blog_search', name = 'search'),
)  

blog 应用views编写:
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_list_or_404, get_object_or_404
from django.template import RequestContext
from django.http import Http404
from blog.models import Post, Category

def index(request):
    """blog列表"""
    categories = Category.objects.all()
    posts = Post.objects.all()
    return render_to_response("blog/index.html",
                  {"posts": posts,
                   "categories": categories
                   },
                  context_instance=RequestContext(request))

def post(request, pk):
    """单篇文章"""
    categories = Category.objects.all()
    post = get_object_or_404(Post, pk=pk)
    return render_to_response("blog/post.html",
                  {"post": post,
                   "categories": categories
                   },
                  context_instance=RequestContext(request))

def detail(request, id):
    try:
        post = Post.objects.get(id=str(id))
    except Post.DoesNotExist:
        raise Http404
    return render(request, 'blog/post.html', {'post' : post})


def category(request, pk):
    """相应分类下的文章检索"""

    try:
        cate = Category.objects.get(pk=pk)
    except Category.DoesNotExist:  ## 读取分类,如果不存在,则引发错误,并404
        raise Http404

    posts = cate.post_set.all() ## 获取分类下的所有文章
    return render_to_response('blog/index.html', ## 使用首页的文章列表模版,但加入了的一个`is_category`开关
        {"posts": posts,
        "is_category": True,
        "cate_name": cate.name,
        "categories": Category.objects.all()},
        context_instance=RequestContext(request))

def blog_search(request):
    if 's' in request.GET:
        s = request.GET['s']
        if not s:
            return render_to_response('blog/index.html')
        else:
            post_list = Post.objects.filter(title__icontains = s)
            if len(post_list) == 0 :
                return render_to_response('blog/archives.html', {'post_list' : post_list,
                                                    'error' : True})
            else :
                return render_to_response('blog/archives.html', {'post_list' : post_list,
                                                    'error' : False})
    return redirect('/')



def search_tag(request, tag):
    print tag,
    try:
        post_list = Post.objects.filter(po_type__iexact = tag) #contains
    except Post.DoesNotExist :
        raise Http404
    return render_to_response('tag.html', {'post_list' : post_list})

模板处理和样式处理

参考源代码这里

最终结果如下:

posted @ 2015-06-24 23:10  shantuwqk  阅读(285)  评论(0编辑  收藏  举报