Issue
I am trying to delete an Item in the QuerySet by Index. I am able to display the items of the QuerySet using print q_set[code_id - 1]
but can not delete it using del q_set[code_id - 1]
. I want to permanently delete the item and not filter excluding that item.
I am getting this error:
TypeError at /lessons/customcode/5/delete
'QuerySet' object doesn't support item deletion
views.py
...
def customcode_view(request):
global q_set
try:
u = User.objects.get(username=request.user)
except:
return render(request,"login_required.html",{})
q_set = customcode.objects.filter(user=u)
if request.method == "POST":
form = CustomcodeForm(request.POST)
if form.is_valid():
cc = form.save(commit=False)
cc.user = u
cc.save()
return HttpResponseRedirect('#BOTTOM')
else:
form = CustomcodeForm()
return render(request, "customcode.html" , {'q_set':q_set,'form':form,})
def deletecode(request,code_id):
code_id = int(code_id)
del q_set[code_id - 1] #this is the problem
return redirect('customcode_view')
...
models.py
...
class customcode(models.Model):
user = models.ForeignKey(User)
name = models.CharField(blank=False,max_length=250)
sourcecode = models.TextField(blank=False)
def __unicode__(self):
return self.name
...
Solution
To permanently get rid of the entry, you don't want to remove the item from the queryset (which is just a volatile view onto your data), but delete the row from the database:
q_set[code_id - 1].delete()
Hth dtk
Answered By - dtk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.