为博客添加分页
创建分页视图 views.py
def post_list(request): # posts = Post.published.all() # return render(request, 'blog/post/list.html', {'posts':posts} object_list = Post.published.all() paginator = Paginator(object_list, 3) # 每页3条记录 page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts':posts})
创建分页模板 pagination.html
在list.html包含分页模板 注:posts是Page对象
{% include "pagination.html" with page=posts%}
打开首页 查看
在post页面 添加邮件分享
创建forms.py
from django import forms class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms.Textarea)
创建处理form的视图
def post_share(request, post_id): post = get_object_or_404(Post, id=post_id, status='published') if request.method == 'POST': form = EmailPostForm(request.POST) if form.is_valid(): cd = form.cleaned_data # send_email.... else: form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form':form})
使用django发送邮件
在setting.py文件中设置smtp服务器参数
EMAIL_HOST = 'smtp.163.com' EMAIL_HOST_USER = '[email protected]' EMAIL_HOST_PASSWORD = 'XXXXXXXXX' EMAIL_PORT = 25
在上面视图中 添加邮件功能
post_url = request.build_absolute_uri(post.get_absolute_url()) subject = '{}({}) recommends you reading "{}"'.format(cd['name'], cd['email'], post.title) message = 'Read "{}" at {}\n\n{}\'s comments {}'.format(post.title, post_url, cd['name'], cd['comments']) send_mail(subject, message, '[email protected]', [cd['to']]) sent = True
为视图添加url映射
url(r'(?P\d+)/share/$', views.post_share, name='post_share'),
为视图添加新模板
{% extends "blog/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %}{% endif %} {% endblock %}E-mail successfully sent
"{{ post.title }}" was successfully sent!
{% else %}Share "{{ post.title }}" by e-mail
在detail.html中添加share的连接
完成之后打开share页面,显示
下面创建一个评论系统
首先为评论 添加数据模型
class Comment(models.Model): post = models.ForeignKey(Post,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post)
同步模型到数据库
在admin 注册 模型
为新模型创建form
class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body')
添加处理form的视图
编辑post_detail视图
comments = post.comments.filter(active=True) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request, 'blog/post/detail.html', {'post':post, 'comments':comments, 'comment_form':comment_form })
在detail.html模版中添加评论
{% with comments.count as total_comments %}{% endif %}{{ total_comments }} comment{{ total_comments | pluralize }}
{% endwith %} {% for comment in comments %}{% empty %}Comment {{ forloop.counter }} by {{ comment.name }} {{ comment.created }}
{{ comment.body | linebreaks }}There are no comments yet.
{% endfor %} {% if new_comment %}Your comment has been added.
{% else %}Add a new comment
打开浏览器 显示
第二天结束