Django博客功能实现—文章评论功能

功能:在A网页提交一个评论Forms_B,提交之后自动刷新页面,能够显示刚刚的画面
思路:利用一个已经创建的表单,通过视图让其在网页中表现出来,填写玩信息之后提交,会提交到一个新的视图里面去做接受,接受之后重定向到另外一个地方。(是什么地方)
步骤:

一、在app里面的forms.py里面新建一个表单:

 1 #blog/forms.py
 2 from django import forms
 3 
 4 class CommentForm(forms.Form):
 5     '''
 6     评论表单
 7     '''
 8     #author使用CharField字段,字段内使用三个参数,分别是widget, max_length, error_messages
 9     author = forms.CharField(
10         #为各个需要渲染的字段指定渲染成什么Html组件,主要是为了添加css样式
11         widget=forms.TextInput(attrs={"id": "author", "class": "comment_input",
12                                                        "required": "required","size": "25", "tabindex": "1"}),
13                           max_length=50,error_messages={"required":"username不能为空",})
14     email = forms.EmailField(widget=forms.TextInput(attrs={"id":"email","type":"email","class": "comment_input",
15                                                        "required":"required","size":"25", "tabindex":"2"}),
16                              max_length=50, error_messages={"required":"email不能为空",})
17     url = forms.URLField(widget=forms.TextInput(attrs={"id":"url","type":"url","class": "comment_input",
18                                                    "size":"25", "tabindex":"3"}),
19                           max_length=100, required=False)
20     comment = forms.CharField(widget=forms.Textarea(attrs={"id":"comment","class": "message_input",
21                                                        "required": "required", "cols": "25",
22                                                        "rows": "5", "tabindex": "4"}),
23                                                 error_messages={"required":"评论不能为空",})
24     article = forms.CharField(widget=forms.HiddenInput())

二、在文章详情视图里面让接入表单

1 def article(request):
2     # 评论表单
3     comment_form = CommentForm({'author': request.user.username,
4                         'email': request.user.email,
5                         'url': request.user.url,
6                         'article': id} if request.user.is_authenticated() else{'article': id})
7     return render(request, 'article.html', locals())

三、在模板中将视图体现出来

 1     <form action="{% url 'comment_post' %}" method="post">
 2     {% csrf_token %}
 3     <p>{{ comment_form.author }}
 4     <label for="author">Name (required)</label></p>
 5 
 6     <p>{{ comment_form.email }}
 7     <label for="email">Email (Will NOT be published) (required)</label></p>
 8 
 9     <p>{{ comment_form.url }}
10     <label for="url">URL</label></p>
11 
12     <p>{{ comment_form.comment }}</p>
13 
14     <p>
15         {{ comment_form.article }}
16         <input name="submit" type="submit" id="submit" tabindex="5" value="Submit" class="button" />
17     </p>
18     </form>

四、模板中的提交链接到URL中

url(r'^comment/post/$', comment_post, name='comment_post'),

五、在视图中接收提交的内容,并且重定向

 1 # 提交评论
 2 def comment_post(request):
 3     try:
 4         #获取表单内填入的内容
 5         comment_form=CommentForm(request.POST)
 6         #进行验证的第一个表单验证
 7         if comment_form.is_vaild():
 8             #获取表单信息
 9             #cleaned_data()用来把接收到的文字清洗为符合django的字符
10             #create是一个在一步操作中同时创建对象并且保存的便捷方法。
11             comment=Comment.objects.create(username=comment_form.cleaned_data["author"],
12                 eamil=comment_form.cleaned_data["email"],
13                 url=comment_form.cleaned_data["url"],
14                 content=comment_form.cleaned_data["comment"],
15                 article_id=comment_form.cleaned_data["article"],
16                 #如果用户已经登录,则获取已经登录的用户,非登录用户将返回None
17                 #此处用的if语句有些特殊。
18                 user=request.user if request.user.is_authenticated() else None)
19             comment.save()  #保存实例
20         else:
21             return render(request, "failure.html", {"reason":comment_form.erros})
22     except Exception as e:
23         logger.error(e)
24         #重定向到进来之前的网页
25         #HTTP_REFERER是http的头文件的一部分,当浏览器向web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器借此获得一些信息用于处理。
26     return redirect(request.META['HTTP_REFERER'])
'''
#判断用户是不是登录,也可以用这个写法,79行的写法也很简单
if request.user.is_authenticated():  #判断用户是否登录
    user=request.user            #获取已经登录的用户
else:
    user=request.user            #非登录用户将返回AnonymousUser
'''

request.META是一个里面包含了所有本次http请求的Header信息,比如用户IP,用户Agent
常见的键值有:
HTTP_REFERER,进站前链接网页,如果有的话。
redirec是重定向
redirec是重定向

作者:岑宇
出处:http://www.cnblogs.com/cenyu/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果文中有什么错误,欢迎指出。以免更多的人被误导。
>
原文地址:https://www.cnblogs.com/cenyu/p/5718181.html