[Django]-How to allow user to delete account in django allauth?

3👍

For issue 1, over-ride the help-text attribute of this field; you can do that in your ModelForm’s init method.

class DeactivateUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['is_active']

    def __init__(self, *args, **kwargs):
        super(DeactivateUserForm, self).__init__(*args, **kwargs)
        self.fields['is_active'].help_text = "Check this box if you are sure you want to delete this account."

    def clean_is_active(self):  
        # Reverses true/false for your form prior to validation
        #
        # You can also raise a ValidationError here if you receive 
        # a value you don't want, to prevent the form's is_valid 
        # method from return true if, say, the user hasn't chosen 
        # to deactivate their account
        is_active = not(self.cleaned_data["is_active"])
        return is_active

For issue 2, you’ll probably want to disable the allauth intermediary logout page. In your settings:

ACCOUNT_LOGOUT_ON_GET = True

And redirect to the logout page in your view logic.

from django.shortcuts import HttpResponseRedirect
from django.core.urlresolvers import reverse_lazy

    # ... in your view
    if user_form.is_valid():
        deactivate_user = user_form.save(commit=False)
        user.is_active = False
        deactivate_user.save()
        return HttpResponseRedirect(reverse_lazy('account_logout')) 

This will redirect to the logout url, which will then forward the user to the url set in your settings via ACCOUNT_LOGOUT_REDIRECT_URL. Your user’s account is now deactivated and they have been logged out.

6👍

Wanted to provide a potential answer for views to both deactivate and delete the User.

# forms.py

from django import forms

class UserDeactivateForm(forms.Form):
    """
    Simple form that provides a checkbox that signals deactivation.
    """
    deactivate = forms.BooleanField(required=True)


class UserDeleteForm(forms.Form):
    """
    Simple form that provides a checkbox that signals deletion.
    """
    delete = forms.BooleanField(required=True)
# views.py

# You could make this DRYer, but sometimes repeating yourself
# for explicitness makes sense.

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.contrib.auth import logout
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.generic import View

from .forms import UserDeactivateForm, UserDeleteForm

class UserDeactivateView(LoginRequiredMixin, View):
    """
    Deactivates the currently signed-in user by setting is_active to False.
    """
    def get(self, request, *args, **kwargs):
        form = UserDeactivateForm()
        return render(request, 'users/user_deactivation.html', {'form': form})

    def post(self, request, *args, **kwargs):
        form = UserDeactivateForm(request.POST)
        # Form will be valid if checkbox is checked.
        if form.is_valid():
            # Make user inactive and save to database.
            request.user.is_active = False
            request.user.save()
            # Log user out.
            logout(request)
            # Give them a success message.
            messages.success(request, 'Account successfully deactivated')
            # Redirect to home page.
            return redirect(reverse('home'))
        return render(request, 'users/user_deactivation.html', {'form': form})


class UserDeleteView(LoginRequiredMixin, View):
    """
    Deletes the currently signed-in user and all associated data.
    """
    def get(self, request, *args, **kwargs):
        form = UserDeleteForm()
        return render(request, 'users/user_deletion.html', {'form': form})

    def post(self, request, *args, **kwargs):
        form = UserDeleteForm(request.POST)
        # Form will be valid if checkbox is checked.
        if form.is_valid():
            user = request.user
            # Logout before we delete. This will make request.user
            # unavailable (or actually, it points to AnonymousUser).
            logout(request)
            # Delete user (and any associated ForeignKeys, according to
            # on_delete parameters).
            user.delete()
            messages.success(request, 'Account successfully deleted')
            return redirect(reverse('home'))
        return render(request, 'users/user_deletion.html', {'form': form})

You then need to create the templates for each of these and the URL routing, but those should be pretty simple.

👤getup8

Leave a comment