How to register with Django admin approval?

Viewed 1373

In the system I created with Django, users should not log in without the admin approval after registration. For example, after the user fills in the registration form, user will see the warning

waiting for admin approval

and cannot login to the system without approval from the admin panel.

views.py

def signup(request):

    form_class = SignUpForm
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            user.first_name = form.data['first_name']
            user.last_name = form.data['last_name']
            user.rank = form.data['rank']
            user.comp_name = form.data['comp_name']
            login(request, user)
            return redirect('/')
    else:
        form = form_class()
    return render(request, 'signup.html', {'form': form})

models.py

class UserProfile(AbstractUser):
    ranks = (
        ('analyst', 'Analyst'),
        ...
    )
    comp_name = models.CharField(max_length=200, default="Choose")
    user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True)
    username = models.CharField(max_length=500, unique=True)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    password = models.CharField(max_length=50)
    email = models.EmailField(max_length=254)
    rank = models.CharField(max_length=200, choices=ranks)
1 Answers

So, you are using a custom user model based on the built-in abstract model. The AbstractUser model has a field named is_active which you can use here.

During the registration process, set the value for is_active to False and use the default AuthenticationForm form for the login view. This form will automatically check for the is_active flag and provide an error when it is False.

Default error messages (you can customize them):

error_messages = {
    'invalid_login': _(
        "Please enter a correct %(username)s and password. Note that both "
        "fields may be case-sensitive."
    ),
    'inactive': _("This account is inactive."),
}

You can get the form from the auth package:

from django.contrib.auth.forms import AuthenticationForm

In your custom admin for the UserProfile model add a filter for the is_active flag:

class UserProfileAdmin(admin.ModelAdmin):
    list_filters = ["is_active"]

That way, you will be able to list non-active profiles and activate them in the admin.

Related