Django2.0 利用ajax打造博客的评论区

首先评论区是需要前端与后台交互的,前端上接受用户的输入。在输入完成后,立马在评论区显示。

首先是urls.py

    path('article//comment',views.comment_view,name='comment'),

再着是 forms.py。

from django import forms
from .models import ArticleComment

class ArticleCommentForm(forms.Form):
    body = forms.CharField(required=True,label="留言",
                              error_messages={'required':'好像空空阿,亲~','max_length':'想说的太多了,精简一些~','min_length':'再输入点内容吧'},
                              max_length=300,min_length=2,widget=forms.Textarea(attrs={'placeholder':'发表以下意见吧'}))

    user_name = forms.CharField(required=True,label="名字",
                               error_messages={'required':'好像空空阿,亲~','max_length':'有这么长的名字??',},
                              max_length=300)
    class Meta:
        model = ArticleComment
        fields = ['body,user_name']


    def clean_body(self):
        message = self.cleaned_data['body']
        if "fuck" in message:
            raise forms.ValidationError('请文明用语')
        return message

    def clean_user_name(self):
        user_name = self.cleaned_data['user_name']
        if "admin" in user_name or "Admin" in user_name:
            raise forms.ValidationError('好像这名字不合适吧')
        return user_name

接下来是views.py。

from .forms import ArticleCommentForm


def comment_view(request,article_id):
    comment = ArticleCommentForm(request.POST)
    if comment.is_valid():
        message = comment.cleaned_data['body']
        user_name = comment.cleaned_data['user_name']
        article = get_object_or_404(Article, pk=article_id)
        new_record = ArticleComment(user_name=user_name, body=message, article=article)
        new_record.save()

        return HttpResponse("")
    else:
        context = {
            'body_error': comment.errors.get('body'),
            'username_error': comment.errors.get('user_name'),
        }
        return HttpResponse(json.dumps(context,ensure_ascii=False),content_type='application/json')

再接着是 html。

{% csrf_token %}

评论留言


再下来是ajax的传输。


你可能感兴趣的:(python,前端)