Django2.0 利用ajax打造博客的評論區

首先評論區是需要前端與後臺交互的,前端上接受用戶的輸入。在輸入完成後,立馬在評論區顯示。

首先是urls.py

    path('article/<int:article_id>/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。

<form id="comment_form" class="bootstrap-frm">
        {% csrf_token %}
        <h1>評論留言</h1>
        <label for="id_body">
            <textarea id="id_body" name="body" placeholder="Send Message To Me"></textarea>
        </label>
        <p style="margin-left: 30px" id="body_error"></p>
        <label for="id_user_name" class="input-group" style="width: 50%">
            <input id="id_user_name" type="text" class="form-control" placeholder="請輸入姓名" aria-describedby="basic-addon2">
        </label>
        <span id="name_error"></span>
        <button class="button" type="submit" id="submit">提交</button>
    </form>

再下來是ajax的傳輸。

<script>
    $(document).ready(function(){
        $.ajaxSetup({
                 data: {csrfmiddlewaretoken: '{{ csrf_token }}' }
            });
        $('#comment_form').submit(function(){
                var body = $("#id_body").val();                 //獲得form中用戶輸入的name 注意這裏的id_name 與你html中的id一致
                var user_name = $("#id_user_name").val();    //同上

                $.ajax({
                    type:"POST",
                    data: {body:body, user_name:user_name},
                    url: "{% url 'comment' article.pk %}", //後臺處理函數的url 這裏用的是static url 需要與urls.py中的name一致#}
                    cache: false,
                    dataType: "html",
                    success: function(result, statues, xml) {
                        if (result) {
                            var jsonData = JSON.parse(result);
                            $("#body_error").html(jsonData['body_error']);
                            $("#name_error").html(jsonData['username_error'])
                        }else{
                            $("#id_body").val("Send Message To Me");
                            $('#id_user_name').val('請輸入名字')
                            window.location.reload()   //提交表單後強行刷新頁面
                        }
                    },
                    error: function(result){
                        alert(result);
                    }
                });
                return false;
            });

        });
</script>

發佈了146 篇原創文章 · 獲贊 94 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章