Search code examples
pythondjangodjango-forms

What is Password-based authentication in the UserCreationForm in Django and how do I remove it?


I made a form that inherits from the UserCreationForm and use class based view that inherits CreateView and when I use runserver and display the form, there is a section at the bottom Password-based authentication that I don't notice

forms.py

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm


class RegisterForm(UserCreationForm):
    """Form to Create new User"""

    class Meta:
        model = get_user_model()
        fields = ["username", "password1", "password2"]

views.py

from django.views.generic import CreateView

from .forms import RegisterForm

from django.urls import reverse_lazy

class SignUp(CreateView):
    form_class = RegisterForm
    template_name = "register.html"
    success_url = reverse_lazy("core:Login")
    def form_valid(self, form):
        user = form.save()
        if user:
            login(self.request, user)
        return super().form_valid(form)

register.html

<h1>signup</h1>

    {{form}}

And when I ran the code I saw this output

output image

So I didn't expect password-based authentication.

My question is about

  1. What exactly is this?
  2. Should it be displayed here?
  3. How do I hide it?

Solution

  • From Django version 5.1 onwards the UserCreationForm has a usable_password field by default. This relates to the feature Django has for setting unusable passwords for users. This is useful in case you're using some kind of external authentication like Single Sign-On or LDAP.

    Since your form seems to be a user facing one and showing this field to your user doesn't make much sense (this particular form is by default geared more towards usage in the admin site) you should simply remove the field from your form by setting it to None:

    class RegisterForm(UserCreationForm):
        """Form to Create new User"""
        usable_password = None
    
        class Meta:
            model = get_user_model()
            fields = ["username", "password1", "password2"]