T
T
The_XXI2021-02-21 15:48:11
Django
The_XXI, 2021-02-21 15:48:11

How to allow certain actions only to authorized users?

Added the ability to log in and register, I'm trying to make the possibility of certain actions only for authorized ones. Here is the code:

def deleteResult(request, item_id):
    if request.user.is_authenticated:
        try:
            item = Results.objects.get(item_id=item_id)
            item.delete()
            return HttpResponseRedirect("/results")
        except Items.DoesNotExist:
            return HttpResponseNotFound("<h2>Result not found</h2>")

How would it work, if the user is logged in, then the item is deleted and everything is fine, if the user is not logged in, then it is not deleted, but it displays an error:
603256350d1c7959439304.png
Changed request.user.is_authenticatedto user.is_authenticated, the effect is the same. How to get rid of the error?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-02-21
@The_XXI

If the user is not authorized, the function returns None, add something there, for example, a redirect to the authorization page

def deleteResult(request, item_id):
    if request.user.is_authenticated:
        try:
            item = Results.objects.get(item_id=item_id)
            item.delete()
            return HttpResponseRedirect("/results")
        except Items.DoesNotExist:
            return HttpResponseNotFound("<h2>Result not found</h2>")
    return HttpResponseRedirect('/register')

Well, it’s better, of course, to use reverse, and not hardcode urls
https://docs.djangoproject.com/en/3.1/ref/urlresolvers/
Well, it would be nice in principle to use the @login_required special decorator https
://docs.djangoproject .com/en/3.1/topics/auth/...

D
Dr. Bacon, 2021-02-21
@bacon

And you try to understand what they write to you in an error, and not stupidly accidentally edit the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question