kenneth koontz
kenneth koontz

Reputation: 869

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))

Upvotes: 3

Views: 586

Answers (1)

miku
miku

Reputation: 188024

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.

Upvotes: 2

Related Questions