Tuesday, August 30, 2011

Re: Unable To Delete Records

On Tue, Aug 30, 2011 at 12:44 PM, Reinout van Rees <reinout@vanrees.org> wrote:
> On 30-08-11 13:05, Showket Bhat wrote:
>>
>> I have created a small application where in i am inserting and
>> deleting records. I am able to delete a single record however when a
>> select all or more then one record it deletes the last record only.. I
>> tried a lot but failed please help I am wring the Code and the Console
>> output here....
>>
>>
>> ===========================================
>> my function to delete a medecine from its table  in views.py
>> ===========================================
>>
>> def delete_medecine(request,medecine={}):
>>     print "------>>",request.POST
>>     list = []
>>     for i in request.POST['del_id']:
>>         m = Medecine.objects.get(id = i)
>>         m.delete()
>>     return HttpResponseRedirect('/medecine')
>
> Ah! Your code is fine, apart from one detail: the request.POST looks like a
> regular dictionary, but it isn't. It is a querydict, look at
> https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict
>
> your request.POST['del_id'] effectively calls __getitem__('del_id') on the
> querydict and the querydict documentation says:
>
> "If the key has more than one value, __getitem__() returns the last value."
>
> Now you know why only the last item gets deleted. It bit my once, too.
>
> What you need to call is request.POST.getlist('del_id'): that will give you
> the list you're expecting.
>
>
>
> Reinout
>

DANGER! - it's actually much much worse than that! Everything that
Reinout said is correct, but remember that POST data is handled as
strings, and strings are iterable collections of characters.

If you had selected 3 items, and your POSTed data looked like this:

del_id=123&del_id=345&del_id=678

and then run this code:

for i in request.POST['del_id']:
    m = Medecine.objects.get(id = i)
    m.delete()

request.POST['del_id'] will return '678', and the for loop will
iterate three times with the values '6', '7' and '8', and you will
delete three unrequested items!

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment