Reputation: 2417
The usecase of my app is to show a list of furnitures in the homepage. There is quick preview button in all those furnitures which when clicked should show its detail information. I tried to use ajax for that. If i click on the furniture quick preview button, I get the clicked furniture slug from which I do the query and get that furniture detail information. Upto this, its working and also the modal is shown but could not show the content. How can i now show the content in the modal-body?
Here is what I have tried
def ajax_furniture_detail(request):
furniture_slug = request.GET.get('slug', None)
qs = Furniture.objects.get(slug=furniture_slug)
cart_obj, new_obj = Cart.objects.new_or_get(request)
context = {
'furniture': model_to_dict(qs),
'cart': model_to_dict(cart_obj),
'status': 'ok'
}
return JsonResponse(context)
{% block content %}
{% include 'furnitures/furnitures_home.html'%}
{% endblock content %}
{% block js %}
{{ block.super }}
<script>
$(document).ready(function(){
$('.quick-view-button').click(function() {
var _this = $(this);
var slug = _this.attr("data-slug");
$.ajax({
url: '/ajax/furniture',
type: "get",
data: {'slug': slug},
success: function(data) {
$('#product-quick-view-modal').modal('show');
$('#product-quick-view-modal').find('.modal-body').html(data.html);
},
error: function(err) {
console.log('error', err);
}
})
})
});
</script>
{% endblock js %}
furnitures_home.html
{% load static %}
<div class="furnitures" id="content">
{% for furniture in furnitures %}
{% if forloop.first %}<div class="row products">{% endif %}
<div class="col-md-4 col-sm-3">
<div class="product">
<div class="image" style="height: 205px;">
<div class="quick-view-button" data-slug={{ furniture.slug }}>
<a href="#" data-toggle="modal" data-target="#product-quick-view-modal" class="btn btn-default btn-sm">Quick view</a>
</div>
{% endif %}
</div>
</div>
</div>
{% endfor %}
</div>
<div class="modal fade" id="product-quick-view-modal" tabindex="-1" role="dialog" aria-hidden="false" style="display: none;">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<p>Hello</p>
<p>{{furniture.name}}</p>
</div>
</div>
</div>
<!--/.modal-dialog-->
</div>
Upvotes: 1
Views: 1311
Reputation: 1793
One neat way to do this is to use a snippet html for product detail and send the product detail html snippet using render_to_string and just replace that html snippet in the modal.
rendered = render_to_string('product_detail_snippet.html', context,
context_instance=RequestContext(request))
return JsonResponse({'product_snippet': rendered})
And in the ajax success:
$('#product-quick-view-modal').find('.modal-body').html(data.product_snippet);
Upvotes: 2