Django个人博客搭建教程---给你的博客留言

一、设计思路

留言功能和评论不太一样,相对简单,我这里没有使用登录的装饰器,也就是不校验是否是登录用户,对于未注册、登录的用户给一个默认头像即可,使用表单提交。

二、前端设计

{% csrf_token %}

对数据库必填字段进行前端校验,通过ajax方式发送表单

三、forms.py

from django import forms
from JiaBlog.models import Comment,Message,Articles


class MessageForm(forms.ModelForm):
    class Meta:
        model = Message
        fields = ['username', 'email', 'phone','title','content']

四、数据库模型设计 

class Message(models.Model):
    username = models.CharField(max_length=256)
    title = models.CharField(max_length=512)
    content = models.TextField(max_length=256)
    email = models.EmailField()
    publish = models.DateTimeField(auto_now_add=True)
    phone = models.CharField(max_length=11,blank=True,default="",null=True)
    messpic = models.CharField(max_length=50,null=True)
    
    # 为了显示
    def __str__(self):
        tpl = ''
        return tpl.format(username=self.username, title=self.title, content=self.content, publish=self.publish)

五、views.py

def savemessage(request):
    if request.method == 'POST':
        form = MessageForm(request.POST)
        data = {}
        if form.is_valid():
            message = form.save(commit=False)
            try:
                message.save()
            except Exception as e:
                data['status'] = '500'
            else:
                thismessage = Message.objects.get(id=message.id)            # 刚入库的留言
                usernames = models.BlogUser.objects.all().values('name')    # 用户表所有name
                usernames = [item[key] for item in usernames for key in item]
                if message.username in usernames:
                    thismessage.messpic = BlogUser.objects.get(name=thismessage.username).userpic.url
                    thismessage.save()
                    data["username"] = thismessage.username
                    data["title"] = thismessage.title
                    data["content"] = thismessage.content
                    data["email"] = thismessage.email
                    data['time'] = thismessage.publish.strftime("%Y-%m-%d %H:%M:%S")
                    data["phone"] = thismessage.phone
                    data["messpic"] = thismessage.messpic
                    email_title = '每一点进步离不开你的宝贵意见,由衷感谢你的支持~'
                    email_body = '已经收到你的宝贵意见,我们会持续改进。--From ArithmeticJia'
                    email = thismessage.email  # 对方的邮箱
                    try:
                        send_mail(email_title, email_body, '[email protected]', [email])
                    except Exception as e:
                        data['status'] = '500'
                        return HttpResponse(json.dumps(data), content_type='application/json')
                    return HttpResponse(json.dumps(data), content_type='application/json')
                else:
                    thismessage.messpic = '/static/JiaBlog/images/img56.jpg'
                    thismessage.save()
                    data["username"] = thismessage.username
                    data["title"] = thismessage.title
                    data["content"] = thismessage.content
                    data["email"] = thismessage.email
                    data['time'] = thismessage.publish.strftime("%Y-%m-%d %H:%M:%S")
                    data["phone"] = thismessage.phone
                    data["messpic"] = thismessage.messpic
                    email_title = '每一点进步离不开你的宝贵意见,由衷感谢你的支持~'
                    email_body = '已经收到你的宝贵意见,我们会持续改进。--From ArithmeticJia'
                    email = thismessage.email  # 对方的邮箱
                    # send_mail(email_title, email_body, '[email protected]', [email])
                    try:
                        send_mail(email_title, email_body, '[email protected]', [email])
                    except Exception as e:
                        data['status'] = '500'
                        return HttpResponse(json.dumps(data), content_type='application/json')
                    return HttpResponse(json.dumps(data), content_type='application/json')

后端尽量多对异常清楚做出处理,这样即使后端处理失败,前端也会有反馈

你可能感兴趣的:(Django)