Deleting Objects

Deleting an object involves one intermediate step: the user is required to confirm the action. This is implemented in the generic delete view by using simple logic—if the HTTP request is GET, it means the user clicked the Delete link and thus needs the confirmation page displayed (which points back to the same URL). If the HTTP request is POST, it means the user clicked the Confirm button and the form has been submitted with an HTTP POST call, in which case the view will proceed with deletion of the object.

There is one caveat with the generic Delete view. It requires a post-delete URL; in other words it needs to know where to take the user after the object has been deleted. The obvious solution would be to reverse-lookup the URL and use it, but since that URL is defined in the very same file (URLConfig) where it will be called from, it will not be evaluated at the moment of the function call. So until this is resolved, we need to use a relative URL, as shown in Listing 4-16.

Listing 4-16. The configuration dictionary for the Delete generic view classrule_delete = { 'model': ClassRule, 'post_delete_redirect': '../..', 'template_name': 'delete_confirm_classrule.html',

The confirmation template simply asks for confirmation and resubmits the data to the same URL, but now with the HTTP POST method:

<form method="post" action="."> <p>Are you sure?</p> <input type="submit" /> </form>

And finally, we make another addition to the URL patterns list:

url(r'Aclassrule/(?P<object_id>\d+)/delete/$', create_update.delete_object, classrule_delete, name='classrule-delete'),

■Note As you might have already guessed, both the Modify and Delete views not only require knowledge about the type of objects they are operating on, but must also uniquely identify the object they are modifying or deleting. The object ID is passed to them from the URL pattern as the object_id variable.

Was this article helpful?

0 0

Post a comment