Reputation: 2590
I'm trying to implement review section in my Django app. The below is my source code for posting and listing reviews of a store. I've already done creating a review with Ajax, but I can't figure out how to show the newly created review after the Ajax call.
Like how like button works in social media, I can easily update the like button based on the response of Ajax call by changing attr()
or html()
. But, this doesn't apply to this review case since it shows a store's reviews with for looping. So I feel like I gotta figure out how to let the for loop run again after the Ajax call.
Have anyone dones this before?
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);
}
});
});
Upvotes: 0
Views: 291
Reputation: 444
You can isolate your reviews loop in a separate template:
reviews.html
{% for i in store.review_set.all %}
...
{% endfor %}
In your HTML:
{% include "reviews.html" %}
In your views.py, you can re-render and return your reviews template as 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}))
Then, in your Ajax success method:
success: function(json) {
// change your reviews div HTML to json['reviews_html'];
}
Upvotes: 1