Django:在模态

时间:2017-11-30 09:55:19

标签: javascript python ajax django django-templates

我的应用程序的用例是在主页中显示家具列表。所有这些家具都有快速预览按钮,点击后应显示其详细信息。我尝试使用ajax。 如果我点击家具快速预览按钮,我会得到点击的家具slug,我可以从中查询并获取家具详细信息。到此为止,它的工作和模态都显示出来,但无法显示内容。我现在如何在模态体中显示内容?

这是我试过的

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>

1 个答案:

答案 0 :(得分:2)

执行此操作的一种巧妙方法是使用片段html获取产品详细信息,并使用render_to_string发送产品详细信息html片段,然后在模式中替换该html片段。

rendered = render_to_string('product_detail_snippet.html', context, 
                       context_instance=RequestContext(request))
return JsonResponse({'product_snippet': rendered})

在ajax的成功中:

$('#product-quick-view-modal').find('.modal-body').html(data.product_snippet);