Shafin M
Shafin M

Reputation: 91

Django user account delete and then return redirect and render

I want to allow a user to delete his account and upon deletion, I want the user to be logged out and see a html page account_deleted.html for confirmation.

students/views.py:

def delete_account(request):
    user = User.objects.get(username=request.user)
    user.delete()

    context = {
        "deleted_msg": "Account has been deleted",
    }
    return render(request, "students/account_deleted.html", context) and redirect("students:logout")

For logout, I'm using the built-in LogoutView function. The logout redirect URL in my settings.py is set to my home page.

students/urls.py:

path('logout/', LogoutView.as_view(), name='logout'),

In case of an account deletion, how can I make the delete_account(request) function return a render and redirect at the same time? Is that even possible? Thanks!

Upvotes: 0

Views: 688

Answers (2)

voodoo-burger
voodoo-burger

Reputation: 2153

You can log the user out before deleting the account by placing logout(request) before your user.delete() line. You will need to import it with from django.contrib.auth import logout.

As Bruno said in his answer, using a redirect instead of render is preferable after a POST request, and you should update your view to only respond to POST requests.

If you are having trouble with your website crashing after a user is deleted, make sure you are using the proper access control in all your views, eg by using the @login_required decorator or the equivalent mixin on all views that require a user to be logged in. If you do this the user will just be redirected to the login page if he or she is not logged in instead of crashing your site.

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77942

First things firsts: your view should 1/ only accept logged in users and 2/ only accept POST requests (you definitely dont want a GET request to delete anything from your database). Also, this:

User.objects.filter(username=request.user)

is useless - you already have the current user in request.user - and potentially dangerous if your auth backend allows for duplicated usernames.

and this:

return render(request, "students/account_deleted.html", context) and redirect("students:logout")

is of course plain wrong. A view returns one single HTTP response, you can't return two (it wouldn't make any sense), and you can't "and" two responses together (well, you can but the result is certainly not what you expect - read the FineManual about the and operator).

The proper solution is to 1/ manually log out the user (cf voodoo-burger's answer), 2/ use the messages framework to inform the user her accont has been deleted, and 3/ redirect to the home page (you ALWAYS want to redirect after a successful post, cf https://en.wikipedia.org/wiki/Post/Redirect/Get for the why).

Upvotes: 1

Related Questions