为博客添加分页
创建分页视图 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
<div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page.number }} of {{ page.paginator.num_pages }}. </span> {% if page.has_next %} <a href="?page={{ page.next_page_number }}">Next</a> {% endif %} </span> </div>
在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<post_id>\d+)/share/$', views.post_share, name='post_share'),
为视图添加新模板
{% extends "blog/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully sent</h1> <p> "{{ post.title }}" was successfully sent! </p> {% else %} <h1>Share "{{ post.title }}" by e-mail </h1> <form action="." method="POST"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send e-mail"> </form> {% endif %} {% endblock %}
在detail.html中添加share的连接
<p> <a href="{% url "blog:post_share" post.id %}">Share this post</a> </p>
完成之后打开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 %} <h2>{{ total_comments }} comment{{ total_comments | pluralize }}</h2> {% endwith %} {% for comment in comments %} <div class="comment"> <p class="info"> Comment {{ forloop.counter }} by {{ comment.name }} {{ comment.created }} </p> {{ comment.body | linebreaks }} </div> {% empty %} <p>There are no comments yet.</p> {% endfor %} {% if new_comment %} <h2>Your comment has been added.</h2> {% else %} <h2>Add a new comment</h2> <form action="." method="POST"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> {% endif %}
打开浏览器 显示
第二天结束