0

delete() function not working in django,

def delete_hardware (request):
    notice = ''
    inventory = get_object_or_404(inventory, id = request.GET.get('id'))
    if inventory:
        inventory.delete()
        notice = "Hardware was deleted"
    return render_to_response('form.html', {'notice': notice},
                              context_instance=RequestContext(request))

......and these are my codes in form.html

<td bgcolor='#f1f1f1'><a onclick="javascript:confirmDelete('/delete/?id={{id}}')">
<img src='{{ MEDIA_URL }}/images/delete.png' width=25 height=25 />
            </a></td>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

2

views.py

def delete_hardware (request, id):
    inventory = get_object_or_404(inventory, pk=id).delete()
    messages.success(request, "Hardware was deleted!")
    return HttpResponseRedirect(reverse('app_name:url_name'))

urls.py

url(r'^delete/(?P<id>\d+)/$', 'delete_hardware', 
    name='delete_hardware'),

I can't provide a full detail codes because your not putting your complete codes in your question. I don't know why but it's up to you. This is only a guide and I hope it will clear your mind. You can only get the data if your form has submit the method=GET

<a href="/delete/{{value.id}}" class="delete-hardware">Delete</a>

<script>
$('.delete-hardware').click(function(){
    var url = $(this).attr('href');
    document.location.href = url;
});
</script>
catherine
  • 22,492
  • 12
  • 61
  • 85
0

it should be request.GET['id']

Just try

def delete_hardware (request):
 notice = " "
 id = request.GET['id']
 try:
   inv = inventory.objects.get(id = id)
   inv.delete()
   notice = "Hardware was deleted"
 except inventory.DoesNotExist:
    raise Http404
 return render_to_response('form.html', {'notice': notice},
                              context_instance=RequestContext(request))
Jonathan
  • 2,728
  • 10
  • 43
  • 73
  • inventory = get_object_or_404(inventory, id = request.GET['id']) --> It doesn't work :( – Cham Yui Canonizado Feb 06 '13 at 07:28
  • is it giving you an error? or just not working? –not working :( – Cham Yui Canonizado Feb 06 '13 at 07:28
  • 1
    @Jonathan If `request.GET` is a dict, it doesn't matter if you use the `[key]` or `.get(key)` syntax – Alex L Feb 06 '13 at 07:30
  • `request.GET` is an instance of a `QueryDict` object which implements standard dictionary methods -- including `.get()`. From the doc, https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict.get *Uses the same logic as __getitem__() above, with a hook for returning a default value if the key doesn't exist.* – K Z Feb 06 '13 at 07:32
  • nothing, it just not working.. it doesn't delete the values in my inventory. – Cham Yui Canonizado Feb 06 '13 at 07:47
  • @ChamYuiCanonizado what happens if you simply hard code the `id` to, say, `1`, and delete it? `inv = inventory.objects.get(id=1); inv.delete()` – K Z Feb 06 '13 at 07:49