我正在尝试在Django应用中实现评论部分。以下是我发布和列出商店评论的源代码。我已经完成了使用Ajax创建审阅的操作,但是我不知道如何在Ajax调用后显示新创建的审阅。
就像按钮在社交媒体中的工作方式一样,我可以通过更改attr()
或html()
来基于Ajax调用的响应轻松更新like按钮。但是,这不适用于此评论案例,因为它显示了带有for循环的商店评论。因此,我觉得我必须弄清楚如何在Ajax调用之后让for循环再次运行。
有人做过吗?
HTML
<div class="review-new">
<div class="my-rating" name="rating"></div>
<textarea class="form-control" rows="5" id="ratingTextarea"></textarea>
<input class="global-btn" stlye="float:right" type="button" value="Submit" id="review-submit"
data-url="{% url 'boutique:post-review-api' store.domainKey %}" data-store-id="{{ store.id }}">
</div>
...
{% for i in store.review_set.all %}
...
{% endfor %}
views.py
class ReviewPost(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request, store_domainKey=None, format=None):
rating = request.data['rating']
content = request.data['content']
store_id = request.data['storeId']
store = Store.objects.get(id=store_id)
new_review = Review()
new_review.store = store
new_review.review_score = rating
new_review.content = content
new_review.created_by = request.user
new_review.save()
reviews = store.review_set.all()
data = {
'reviews': reviews
}
return Response(data)
ajax.js
$(document).on("click", "#review-submit", function(e) {
e.preventDefault();
var _this = $(this);
var url = _this.attr("data-url");
var rating = _this.attr("data-rating");
var storeId = _this.attr("data-store-id");
var content = $("#ratingTextarea")[0].value;
$.ajax({
url: url,
method: "POST",
data: {
csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(),
rating: rating,
content: content,
storeId: storeId
},
success: function(res) {
console.log(res);
},
error: function(error) {
console.log(error);
}
});
});
答案 0 :(得分:1)
您可以在单独的模板中隔离评论循环:
reviews.html
{% for i in store.review_set.all %}
...
{% endfor %}
在您的 HTML 中:
{% include "reviews.html" %}
在您的 views.py 中,您可以重新渲染评论模板并将其返回为HTML:
import json
from django.template import loader
from django.shortcuts import HttpResponse
...
reviews_html = loader.render_to_string('reviews.html', context={'store': store})
return HttpResponse(json.dumps({'reviews_html': reviews_html}))
然后,以您的 Ajax 成功方法:
success: function(json) {
// change your reviews div HTML to json['reviews_html'];
}