环境Windows 7
pycharm +Django1.8 + python3.5
配置环境 此处省略10000字...
项目源码文件在附件
博客实现功能如下:
通过邮件分享博客
博客评论系统
支持标签功能
支持相似文章推荐
支持站点地图
支持RSS订阅
支持搜索引擎功能
首页预览图
后台预览图
创建项目
django-admin startproject mysite
初始化数据库
python manage.py migrate
启动开发服务器
python manage.py runserver
打开浏览器查看 http://127.0.0.1:8000/
下面表示django正常运行
如果需要在其他端口运行,执行
python manage.py runserver 127.0.0.1:8001
修改setting.py文件
Asia/Shangha
创建一个应用
python manage.py startapp blog
设计博客的数据模型
编辑blog下面的models.py文件
# -*- coding:utf-8 -*- from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') # slug 表示短标题 # 这里的unique_for_date 表示publish 和 slug 一起限定post,不能有2个都同样的post,即有可能slug是一样的 author = models.ForeignKey(User, related_name='blog_posts') # related_name 关联对象反向查找源对象 即User.post_set.all() 也可以 换成 User.blog_posts.all() body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) # 创建对象的时候自动添加时间 只运行一次 updated = models.DateTimeField(auto_now=True) # 保存对象的时候,自动更新, 可以执行多次 status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) # 指定查询数据库的结果降序 def __str__(self): return self.title # django管理站点显示对象的表示
激活应用,在setting.py INSTALLED_APPS中添加blog
创建应用迁移
python manage.py makemigrations blog
python manage.py migrate
为你的模型创建管理站点
创建一个超级用户
python manage.py createsuperuser
打开http://127.0.0.1:8000/admin/ 显示
注册post模型修改admin.py
from django.contrib import admin from .models import Post admin.site.register(Post)
自定义模型后台展示 修改admin.py
class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') prepopulated_fields = {'slug': ('title', )} # 使用title 预填充 raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ['status', 'publish'] admin.site.register(Post,PostAdmin)
打开后台post 显示
创建模型管理器 models.py
添加管理器类
class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published')
在模型中使用
published = PublishedManager()
创建列表和详细视图 views.py
def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts':posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post':post})
为你的视图添加url,urls.py
urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), ]
映射urls.py到主urls,urls.py
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog' ))
构建post的绝对url,在模板中会用到 models.py
def get_absolute_url(self): return reverse('blog:post_detail', args=[ self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), # 添加前面的0 self.slug ])
为视图创建模板
创建模板目录结构
编辑base.html
{% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> <div id="sidebar"> <h2>My blog</h2> <p>This is my blog</p> </div> </body> </html>
list.html
{% extends "blog/base.html" %} {% block title %}My Blog%{% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> </h2> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body | truncatewords:30 | linebreaks }} {% endfor %} {% endblock %}
访问首页显示
detail.html
{% extends "blog/base.html" %} {% block title %}{{ post.title }}{% endblock %} {% block content %} <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body | linebreaks }} {% endblock %}
访问post页显示
第一天结束