reedvoid
reedvoid

Reputation: 1253

Django performing an action on a model via link

I want to, say, delete a record via a button on a website. How would I do that?

Thus far every "button" or action I've done has to do with forms, which is handled via "post". The URL would stay the same, just a matter if it's a get or a post that the content and actions are different.

But if I want to delete something, I really don't think I want to create a URL that's like "/delete_record" or something like that. Also, don't really think every button needs to be a form either.... say there are 10 records and I could delete any one of them, that'd be like 10 forms?

Maybe this is something I'd do with Javascript or something?

Upvotes: 2

Views: 1657

Answers (1)

elssar
elssar

Reputation: 5871

You could create a url with an identifier to the object you want to delete and in the view, just delete the object.

Say you want to delete an object of the Record type. Create an url like so

url(r'^record/delete/(?P<id>)/$', 'delete_record_view', name='delete-record-url')

A view like so

def delete_record_view(request, id):
    obj = get_object_or_404(Record, pk=id)
    # some validation here to make sure the user clicking the link can delete the object
    obj.delete()

And in the template

<a href="{% url 'record-delete-link' record_object.id %}">Delete</a>

Upvotes: 4

Related Questions