pass value to bootstrap modal form with django

前端 未结 1 679
予麋鹿
予麋鹿 2021-01-07 13:58

When I use bootstrap modal for my form its only show first value.

here my template.html

{% for company in companys %}

    <         


        
1条回答
  •  甜味超标
    2021-01-07 14:13

    Your ajax modal will always return the same value inside modal because:
    - Modal has this data-target="#modal-default2" as the target, however, your loop contains the modal body, with the id id="modal-default2", which will render modal as much as your loop goes.

    So what you can do is to define a unique ID for each modal with the ID of each company modal-default{{company.id}}:

    {% for company in companys %}
        ''' rest of codes '''
        
        ''' rest of codes '''
    
        
        ''' rest of codes '''
    {% endfor %}
    

    But this method is not effective if you have a lot of data, it will render lots of html codes.

    Another option

    With AJAX and one modal.

    Your html would be:

    {% for company in companys %}
        {{ company.name }}
        {{ company.desc }}
    
         
    {% endfor %}
    {% csrf_token %}
    
    
    
    

    AJAX

    $(document).on('click','.delete-company',function(){
        var id = $(this).data('id');
    
        $.ajax({
            url:'',
            type:'POST',
            data:{
                'id':id,
                'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
            },
            success:function(data){
                $('#modal-default .modal-dialog').html($('#modal-default .modal-dialog',data));
                $('#modal-default').modal('show');
            },
            error:function(){
                console.log('error')
            },
        });
    });
    

    And your views would be:

    change your url from CompanyListView.as_view() to companyListView

    def companyListView(request):
        context = {}
        companys = models.Company.objects.all()
        if request.method == 'POST' and request.is_ajax():
            ID = request.POST.get('id')
            company = companys.get(id=ID) # So we send the company instance
            context['company'] = company
        context['companys'] = companys
        return render(request,'template.html',context)
    

    0 讨论(0)
提交回复
热议问题