Deleting features

We next want to let the user delete an existing feature. To do this, we'll add a Delete Feature button to the "edit feature" view. Clicking on this button will redirect the user to the "delete feature" view for that feature.

Edit the editFeature.html template, and add the following highlighted lines to the<form> section of the template:

  <form method="POST" action="">
    <table>
      <tr>
        <td></td>
        <td align="right">
          <input type="submit" name="delete"
                 value="Delete Feature"/>
        </td>
      </tr>
      {{ form.as_table }}
      ...

Notice that we've used<input type="submit"> for this button. This will submit the form, with an extra POST parameter named delete. Now, edit the views.py module again, and add the following to the top of the editFeature() function:

  if request.method == "POST" and "delete" in request.POST:
    return HttpResponseRedirect("/shape-editor/deleteFeature/"
                                +shapefile_id+"/"+feature_id)

We next want to set up the "delete Feature" view. Edit urls.py and add the following to the geodjango.shapeEditor.views list of URL patterns:

  (r'^shape-editor/deleteFeature/(?P<shapefile_id>d+)/' +
   r'(?P<feature_id>d+)$', 'deleteFeature'),

Next, create a new file named deleteFeature.html in the templates directory, and enter the following text into this file:

<html>
    <head>
        <title>ShapeEditor</title>
    </head>
    <body>
        <h1>Delete Feature</h1>
        <form method="POST">
            Are you sure you want to delete this feature?
            <p/>
            <button type="submit" name="confirm"
                    value="1">Delete</button>
            &nbsp;
            <button type="submit" name="confirm"
                    value="0">Cancel</button>
        </form>
    </body>
</html>

This is a simple HTML form that confirms the deletion. When the form is submitted, the POST parameter named confirm will be set to 1 if the user wishes to delete the feature. Let's now implement the view that uses this template. Edit views.py and add the following new view function:

def deleteFeature(request, shapefile_id, feature_id):
  try:
    feature = Feature.objects.get(id=feature_id)
  except Feature.DoesNotExist:
    raise Http404

  if request.method == "POST":
    if request.POST['confirm'] == "1":
      feature.delete()
    return HttpResponseRedirect("/shape-editor/edit/" +
                                shapefile_id)

  return render_to_response("deleteFeature.html")

As you can see, deleting features is quite straightforward.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.34.62