关闭

Django在OS X下的编程实战(三)-构建博客的高级功能

标签: djangopython
365人阅读 评论(0) 收藏 举报
分类:

在之前的两篇文章Django在OS X下的编程实战(一)构建一个博客系统Django在OS X下的编程实战(二)操作博客数据模型主要利用Django的应用模版很快的构建了一个博客系统,大部分都是使用的模版内生的功能。这一篇主要开始大规模定制模版,实现更高级和定制化的功能。

使用电子邮件分享博客文章。

根据各种博客的共同特征,这个功能要实现包涵了:

创建一个动作入口,一个超链接去进入表单

创建一个表单用来填写共享帖子和邮件相关信息,表单提交完成分享


接下来分解每一步:

1. 创建表单form.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)

2. 在view.py里面处理表单响应

From .forms import EmailPostForm

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
     else:
          form = EmailPostForm()
     return render(request, 'blog/post/share.html', {'post':post,'form':form})

3. 发送邮件功能使用python的邮件库,把下面代码增加到view.py里面。

from django.core.mail import send_mail
send_mail('Django mail','This email was sent with Django.','admin@test.com',['admin@test.com'],fail_silently=False)
因此,view.py看上去像下面

from .forms import EmailPostForm
from django.core.mail import send_mail

def post_share(request,post_id):
     post = get_object_or_404(Post,id=post_id,status='published')
     sent = False
     if request.method == 'POST':
          form = EmailPostForm(request.POST)
          if form.is_valid():
               cd = form.cleaned_data
               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,'admin@test.com',[cd['to']])
               sent = True
     else:
          form = EmailPostForm()
     return render(request, 'blog/post/share.html', {'post':post,'form':form,'sent':sent})

4. 最后输出显示模版如下

{% extends "blog/base.html" %}
{% block title %}Share a post{% endblock%}
{% block content%}
{% if sent %}
<h1>Email sent successfully.</h1>
<p>
"{{post.title}}" was successfully sent to {{cd.to}}.
</p>
{% else %}
<h1>Share "{{post.title}}" by email</h1>
<form action="." method='post">
{{form.as_p}}
{% csrf_token %}
<input type="submit" value="Send email">
</form>
{% endif %}
{% endblock %}

创建评论系统

这个功能和用邮件共享帖子是一样的,也是需要表单,响应和显示。唯一多出来的是评论和帖子是不同的数据模型。

1. 在models.py创建评论模型

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))

2. 创建的数据模型同步到数据库

python manage.py makemigrations blog
python manage.py migrate

3. 把数据模型挂在站点admin.py上面去。

from .models import Post, Comment

class CommentAdmin(admin.ModelAdmin):
     list_display = ('name','email','post','created','active')
     list_filter = ('active','created','updated')
     search_fileds=('name','email','body')
admin.site.register(Comment, CommentAdmin)

4. 在forms.py创建表单,并且在models.py里面响应事件

from .models import Comment

class CommentForm(forms.ModelForm):
     class Meta:
          model = Comment
          fields=('name','email','body')

from .models import Post, Comment
from .models import EmailPostForm, CommentForm

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)
     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})

5. 最后也是需要调整view的显示模版,在post_detail.html里面增加评论列表。这一部分代码我就不贴了。

最后一个功能,就是给帖子打标签,这一部分,我略过,有兴趣的找django-taggit的文档来看。总归一句话,别再想着写代码了,你想写的,都被人写完了,你想着怎么整合拼装就好了,除非你要做底层的程序员。



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13919次
    • 积分:298
    • 等级:
    • 排名:千里之外
    • 原创:13篇
    • 转载:6篇
    • 译文:3篇
    • 评论:0条
    文章分类