利用Django编写简单的Blog(八)

接上节:http://www.cnblogs.com/hellopython/archive/2013/05/22/3093606.html

实习分类目录功能

修改models.py为

from django.db import models
from django.contrib.auth.models import User

# Create your models here. 
class Category(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=40, unique=True)
    description = models.TextField()

    class Meta:
        verbose_name_plural = "Categories"

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return "/categories/%s/" % self.slug

class Post(models.Model):
    title = models.CharField(max_length=200)
    pub_date = models.DateTimeField()
    text = models.TextField()
    slug = models.SlugField(max_length=40, unique=True)
    author = models.ForeignKey(User)
    categories = models.ManyToManyField(Category, blank=True, null=True, through='CategoryToPost')

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return "/%s/%s/%s/" % (self.pub_date.year, self.pub_date.month, self.slug)

class CategoryToPost(models.Model):
    post = models.ForeignKey(Post)
    category = models.ForeignKey(Category)

接着,编辑admin.py

 1 import models
 2 from django.contrib import admin
 3 from django.contrib.auth.models import User
 4 
 5 class CategoryAdmin(admin.ModelAdmin):
 6     prepopulated_fields = {"slug": ("title",)}
 7 
 8 class CategoryToPostInline(admin.TabularInline):
 9     model = models.CategoryToPost
10     extra = 1
11     
12 class PostAdmin(admin.ModelAdmin):
13     prepopulated_field = {"slug":("title",)}
14     exclude = ('author',)
15     inlines = [CategoryToPostInline]
16 
17     def save_model(self,request,obj,form,change):
18         obj.author = request.user
19         obj.save()
20 
21 admin.site.register(models.Post,PostAdmin)
22 admin.site.register(models.Category, CategoryAdmin)

 接着编辑views.py

 1 # Create your views here.
 2 from django.shortcuts import render_to_response
 3 from django.core.paginator import Paginator, EmptyPage
 4 from blogengine.models import Post, Category
 5 
 6 def getPosts(request, selected_page=1):
 7     # Get all blog posts
 8     posts = Post.objects.all().order_by('-pub_date')
 9 
10     # Add pagination
11     pages = Paginator(posts, 5)
12 
13     # Get the specified page
14     try:
15         returned_page = pages.page(selected_page)
16     except EmptyPage:
17         returned_page = pages.page(pages.num_pages)
18 
19     # Display all the posts
20     return render_to_response('posts.html', { 'posts':returned_page.object_list, 'page':returned_page})
21 
22 def getPost(request, postSlug):
23     # Get specified post
24     post = Post.objects.filter(slug=postSlug)
25 
26     # Display specified post
27     return render_to_response('single.html', { 'posts':post})
28 
29 def getCategory(request, categorySlug, selected_page=1):
30     # Get specified category
31     posts = Post.objects.all().order_by('-pub_date')
32     category_posts = []
33     for post in posts:
34         if post.categories.filter(slug=categorySlug):
35             category_posts.append(post)
36 
37     # Add pagination
38     pages = Paginator(category_posts, 5)
39 
40     # Get the category
41     category = Category.objects.filter(slug=categorySlug)[0]
42 
43     # Get the specified page
44     try:
45         returned_page = pages.page(selected_page)
46     except EmptyPage:
47         returned_page = pages.page(pages.num_pages)
48 
49     # Display all the posts
50     return render_to_response('category.html', { 'posts': returned_page.object_list, 'page': returned_page, 'category': category})

 

 

 在template目录下新建个文件 category.html, 写入如下代码

 1 {% include 'header.html' %}
 2         <h1>Posts for {{ category.title }}</h1>
 3         {% if posts %}
 4         {% for post in posts %}
 5         <h1><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h1>
 6         {{ post.text }}
 7         {% endfor %}
 8         <br />
 9         {% if page.has_previous %}
10         <a href="/{{ page.previous_page_number }}/">Previous Page</a>
11         {% endif %}
12         {% if page.has_next %}
13         <a href="/{{ page.next_page_number }}/">Next Page</a>
14         {% endif %}
15         {% else %}
16         <p>No posts matched</p>
17         {% endif %}
18 {% include 'footer.html' %}

 再编辑urls.py

 1 from django.conf.urls import patterns, include, url
 2 
 3 # Uncomment the next two lines to enable the admin:
 4 from django.contrib import admin
 5 admin.autodiscover()
 6 
 7 urlpatterns = patterns('',
 8     # Examples:
 9     # url(r'^$', 'DjangoBlog.views.home', name='home'),
10     # url(r'^DjangoBlog/', include('DjangoBlog.foo.urls')),
11 
12     # Uncomment the admin/doc line below to enable admin documentation:
13     # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
14 
15     # Uncomment the next line to enable the admin:
16 url(r'^admin/', include(admin.site.urls)),
17 url(r'^$', 'blogengine.views.getPosts'),
18 url(r'^(?P<selected_page>\d+)/?$', 'blogengine.views.getPosts'),
19 # Blog posts
20 url(r'^\d{4}/\d{1,2}/([-a-zA-Z0-9]+)/?$', 'blogengine.views.getPost'),
21 # Flat pages
22 url(r'', include('django.contrib.flatpages.urls')),
23 )

 重新导入数据库 python manage.py syncdb

打开setings.py,并在INSTALLED_APPS下增加

1 'django.contrib.comments',

 重新导入数据库 python manage.py syncdb

打开urls.py,增加

1 # Comments
2 url(r'^comments/', include('django.contrib.comments.urls')),

接着编辑 posts.html

 1 {% include 'header.html' %}
 2         {% for post in posts %}
 3         <h1><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h1>
 4         {{ post.text }}
 5         {% endfor %}
 6         <br />
 7         {% if page.has_previous %}
 8         <a href="/{{ page.previous_page_number }}/">Previous Page</a>
 9         {% endif %}
10         {% if page.has_next %}
11         <a href="/{{ page.next_page_number }}/">Next Page</a>
12         {% endif %}
13 {% include 'footer.html' %}

然后:category.html

 1 {% include 'header.html' %}
 2         {% load comments %}
 3         <h1>Posts for {{ category.title }}</h1>
 4         {% if posts %}
 5         {% for post in posts %}
 6         <h1><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h1>
 7         {{ post.text }}
 8         {% get_comment_count for post as comment_count %}
 9         <h3>Comments: {{ comment_count }}</h3>
10         {% endfor %}
11         <br />
12         {% if page.has_previous %}
13         <a href="/{{ page.previous_page_number }}/">Previous Page</a>
14         {% endif %}
15         {% if page.has_next %}
16         <a href="/{{ page.next_page_number }}/">Next Page</a>
17         {% endif %}
18         {% else %}
19         <p>No posts matched</p>
20         {% endif %}
21 {% include 'footer.html' %}

single.html

 1 {% include 'header.html' %}
 2         {% load comments %}
 3         {% for post in posts %}
 4         <h1><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h1>
 5         <h3>{{ post.pub_date }}</h3>
 6         {{ post.text }}
 7         <h3>By {{ post.author.first_name }} {{ post.author.last_name }}</h3>
 8         <h3>Categories: {% for category in post.categories.all %} {{ category.title }} {% endfor %}</h3>
 9         {% get_comment_count for post as comment_count %}
10         <h3>Comments: {{ comment_count }}</h3>
11         <ol>
12         {% get_comment_list for post as comments %}
13         {% for comment in comments %}
14         <li>{{ comment }}</li>
15         {% endfor %}
16         </ol>
17         {% render_comment_form for post %}
18         {% endfor %}
19         <br />
20         {% if page.has_previous %}
21         <a href="/{{ page.previous_page_number }}/">Previous Page</a>
22         {% endif %}
23         {% if page.has_next %}
24         <a href="/{{ page.next_page_number }}/">Next Page</a>
25         {% endif %}
26 {% include 'footer.html' %}

 views.py增加

1 fromdjango.templateimportRequestContext

然后修改 views.py getPost最后一句为

returnrender_to_response('single.html',{'posts':post},context_instance=RequestContext(request))

 

接下来就是增加RSS功能了

settings.py 

'django.contrib.syndication',

urls.py

from blogengine.views import PostsFeed


'django.contrib.syndication',

views.py

1 from django.contrib.syndication.views import Feed
 1 class PostsFeed(Feed):
 2     title = "My Django Blog posts"
 3     link = "feeds/posts/"
 4     description = "Posts from My Django Blog"
 5 
 6     def items(self):
 7         return Post.objects.order_by('-pub_date')[:5]
 8 
 9     def item_title(self, item):
10         return item.title
11 
12     def item_description(self, item):
13         return item.text

 

posted on 2013-05-23 22:37  hellopython  阅读(242)  评论(0编辑  收藏  举报

导航