简体   繁体   中英

Get Django Item ID In Ajax URL

I have a select box in an item edit page, which i would like to be populated via an Ajax call with the saved values.

<script type="text/javascript">
    $(document).ready(function() {
        $('#editPrefabLineclassBox').on('change', function() {
            var selected = this.value;
                $.ajax({
                    url: '/edit-prefab/,
                    type: 'POST',
                    data: {
                        csrfmiddlewaretoken: '{{ csrf_token }}',
                        lineclassSelected: selected
                    },
                    success: function(data) {
                        var name, select, option;
                        select = document.getElementById('editPrefabNameBox');
                        select.options.length = 0;
                        for (name in data) {
                            if (data.hasOwnProperty(name)) {
                                select.options.add(new Option(data[name], name));
                            }
                        }
                    }
                });
            });
        })
</script>

The url i am using in the call is /edit-prefab/. The problem i am having is, the url of the page in Django is actually /edit-prefab/{{ material_item.id }}, only i am not sure how to pass this id to javascript to use in the Ajax call. With just the /edit-prefab/, the page is not found.

After populating the select with the list of items, i would like to have preselected the saved values of the item being edited. I am sure i could populate everything as needed. Its just the setting up of the url that has me a little confused

I have tried passing the id of the item through the view to the template with JSON.dumps, and then parse the variable in JS to use in the url, but i keep getting an unexpected column error when parsing, as from what i know only a dict can be parsed correctly with JSON.

Is there anyone who could please help with this?

EDIT:

def editprefabitem(request, materialitem_id):
    context = dict()
    mat_item = MaterialItem.objects.get(id=materialitem_id)

    context['itemid'] = json.dumps(mat_item.id)    
    context['lineclass'] = json.dumps(mat_item.lineclass)
    context['itemname'] = json.dumps(mat_item.name)
    context['diameter'] = json.dumps(mat_item.diameter)
    context['quantity'] = json.dumps(mat_item.quantity)

    if request.method == 'POST':
        if 'lineclassSelected' in request.POST:
            lclass = Lineclass.objects.filter(lineclassname=request.POST['lineclassSelected'])\
            .values_list('itemname', flat=True).distinct()
        request.session['lineclassselected'] = request.POST['lineclassSelected']
        lineclass = valuesquerysettodict(lclass)
        return HttpResponse(json.dumps(lineclass), content_type='application/json')

    if 'itemSelected' in request.POST:
        item = Lineclass.objects.filter(itemname=request.POST['itemSelected'])[0]
        diams = Lineclass.objects.filter(itemname=item.itemname).values_list('dn1', flat=True).distinct()
        request.session['itemselected'] = request.POST['itemSelected']
        diameters = valuesquerysettodict(diams)
        return HttpResponse(json.dumps(diameters), content_type='application/json')

    if 'diamSelected' in request.POST:
        request.session['diameterselected'] = request.POST['diamSelected']

    if 'editPrefabQuantityBox' in request.POST:
        code = Lineclass.objects.filter(lineclassname=request.session['lineclassselected'])\
            .filter(itemname=request.session['itemselected']).filter(dn1=request.session['diameterselected'])[0]\
            .code

        mat_item.name = request.session['itemselected'],
        mat_item.type = 'Prefabrication',
        mat_item.lineclass = request.session['lineclassselected'],
        mat_item.diameter = request.session['diameterselected'],
        mat_item.quantity = request.POST['editPrefabQuantityBox'],
        mat_item.workpack = Workpack.objects.get(id=request.session['workpackselected']),
        mat_item.code = code,
        mat_item.datecreated = datetime.datetime.today(),
        mat_item.createdby = request.user.username

        mat_item.save()
        return HttpResponseRedirect('/prefabs/')

return render_to_response('editprefab.html', context, context_instance=RequestContext(request))

The context['itemid'], context['lineclass'] etc, is where i am grabbing the current values of the item and trying to send them through to the template to be parsed by javascript to set the default values for editing in the select boxes, and provide the items id in the url.

The valuesquerysettodict() function, is a small snippet i found, to convert a Models, values_list into a JSON serializable dict to populate the select based on the parameter that was sent through from Ajax. The reason i am using it, is if i return Lineclass.objects.all(), there are a lot of items in the queryset, with the same name, but different itemcode, so i am using a values_list to try and get unique item names to use with the select.

I am sure i am going wrong somewhere i am just not sure where.

thank you for any help you could give.

So I assume you're making your AJAX call at the click of a submit button. Either way, you can supply the Django variable in the value attribute of any tag and retrieve it like this.

In the value attribute of your submit button, pass the Django ID as such:

<button type="submit" value="{{ material_item.id }}" id="submit-button"></button> Now, in your AJAX request, you can retrieve the ID and send it with your AJAX request like this:

$(document).ready(function(event){ 
    $(document).on('click', '#submit-button' , function(event){
    event.preventDefault();
    var pk = $(this).attr('value');
    data:{
         'id': pk,
    }
    ....
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM