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