Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting objects with django framework or javascript/AJAX

I have a page that has a simple form. When I submit this form I am redirected to the same page with the new objects created. I'd like to add inline links to the right of every object created to delete and edit. Would I do this with django or would I use javascript/AJAX to handle this? I'm just a little confused on the approach that I should take. Any suggestions?

Here's what my view currently looks like:

def events(request):
    the_user = User.objects.get(username=request.user)
    event_list = Event.objects.filter(user=the_user)
    if request.POST:
        form = EventForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = EventForm(initial={'user':the_user})
    return render_to_response("events/event_list.html", {
        "form": form,
        "event_list": event_list,
    }, context_instance=RequestContext(request))
like image 697
kenneth koontz Avatar asked Aug 05 '26 03:08

kenneth koontz


1 Answers

Usually, you would write another view function, e.g. delete_event(request, event_id) and wire it up in urls.py. Inside the delete view, you would use the provided Model.delete() function to remove the object from the database.

The choice whether to use ajax or not is mostly a matter of taste - you would need to issue a request via javascript to a similar function as I described above, which would take care of the logic.

Some additional overhead is present (when using ajax) in terms of updating the page appropriately.

The proper http verb for deletes would be DELETE, but since this is not usually supported out of the box, you'll use POST.

like image 94
miku Avatar answered Aug 06 '26 17:08

miku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!