How to protect URLs in Django

Is there a way to prevent users from accessing some (or all) of the URLs in the application? For example, I am following a Django tutorial, and one example has a URL:

#music/album/<pk>/delete
url(r'image/(?P<pk>[0-9]+)/delete/$', views.ImageDelete.as_view(), name='image-delete'),

which deletes the database record, gives pkas a parameter. Of course, now you can delete this entry by simply copying the URL with any existing primary key, so what is the best way to avoid it? Thanks

EDIT. Based on the answers and comments, I decided to dwell on them in more detail. I actually use DeleteViewforms with a request POSTlike @solarissmoke suggested in response.

<form action="{% url 'album:image-delete' image.id%}" method="post" style="display: inline;">
{% csrf_token %}
    <input type="hidden" name="image_id" value="{{ image.id }}"/>
        <button type="submit" class="btn btn-default btn-sm">
            <span class="glyphicon glyphicon-trash"></span>
        </button>
</form>

and in mine views.py:

class ImageDelete(DeleteView):
    model = Album
    # if you successfully delete the object, page redirects to <homepage>
    success_url = reverse_lazy('album:index')

, , URL (, ) /, , . . Facebook, imeage/post, URL- . , Facebook, , URL-, . !

+4
2

, HTTP GET , ( ) , .

POST , .. Django . DeleteView:

, . , POST. GET, , POST URL-.

:

  • , , - . Django (, CSRF) . , , , .

  • .

  • , URL- ( ).

+2

... :

user = request.user
if user.is_authenticated() and user.profile.can_delete_image(image_pk):
    # only then, image can be deleted by this user
    # can_delete_image(image_pk) is defined by you
else: 
    raise DeletePermissionDenied # you can define your own Exception, just for fun
+1

All Articles