Django中的Ajax呼叫

I'm using Django. I created a function for delete button. it's working fine but the problem is : There is a template which is shared in two places (one is for url: /employer/job/edit and other is for vendor/job/edit) template is same for both. my code is as following which is working fine with /employer/job/edit but not working for vendor/job/edit. Button code is :

<a style="cursor:pointer;" class="delete"
   data-pk="{{ i.id }}" data-appname="employer" data-modelname="office">
    <i class="fa fa-times font-18 iconcolor pt3 float-r" ></i>
</a>

JQUERY IS :

 $('.delete').click(function() {
     appname = $(this).data('appname');
     modelname = $(this).data('modelname');
     pk = $(this).data('pk');
     delete_this = $(this);
     $.ajax({
        url: "/delete_button/" + appname + "/" + modelname + "/" + pk + "/",
        type: "DELETE",
        success: function() {
            // Remove the HTML Element which represents you data
            delete_this.parent().parent().parent().parent().remove();

             $('#'+pk).remove();
             location.reload(true);
        }
    });
 });

and my function which i wrote in view.py is:

def delete_data(request, app_name, model_name, pk):
    try:
        model_name = get_model(app_name, model_name)
        if request.method=='DELETE':
            model_name.objects.get(id=pk).delete()
            return HttpResponse('deleted', status=200)
    except Exception, e:
        return HttpResponse('error', status=500)

what is wrong, i'm doing. please help me out!!

Replying to the question raised in the first comment, if you have the

  • django.template.context_processors.request in Django >= 1.8
  • django.core.context_processors.request in Django < 1.8

context preprocessor added to your TEMPLATE_CONTEXT_PROCESSORS setting, then you could access the name of the current app in the template via {{ request.resolver_match.app_name }}.

The model_name you can supply via the context and if you don't use the TEMPLATE_CONTEXT_PROCESSORS you can also hardcode the appname there.

views.py

# other view code ...
c = Context({
    # possibly other context variables
    'current_app': 'employer',
    'model_name': 'office'
})

return render(request, 'my/template.html', c)

This way your link markup would look like this

<a ... data-appname="{{ request.resolver_match.app_name }}" 
       data-modelname="{{ model_name }}">...</a>

or when using the hardcoded app name:

<a ... data-appname="{{ current_app }}" 
       data-modelname="{{ model_name }}">...</a>

Just as an obvious note, be careful with this kind of code and make sure that these views are secured in terms of parameters they allow, sufficient user permissions for a request and model instances they will be able to delete.