DEV Community

codewitgabi
codewitgabi

Posted on

How to remove help text from django's UserCreationForm

So I've had a hard time creating users with the in-built UserCeationForm in django mostly because of the help text for password1 field so I tried looking into it critically get work my way around it. After much trial, I was able to get it done so that's what I'll be sharing with you guys today.

I'll believe you already have a little knowledge of django so I won't be starting from the very basics. I've created my project and named my app as myapp.

I'll start by creating a forms.py file where we'll be creating our custom user registration form.

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

# get the current user model
User = get_user_model()

class CustomUserForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["password1"].help_text = ""

    class Meta:
        model = User
        # add needed fields
        fields = ["username", "email", "password1", "password2"]


Enter fullscreen mode Exit fullscreen mode

Once this is done, go into your views.py file and add the following

from django.shortcuts import render, redirect
from .forms import CustomUserForm

def register(request):
    form = CustomUserForm()
    # handle form submission
    if request.method == "POST":
        form = CustomeUserform(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/path-to-redirect-to/")
    return render(request, "register.html", {"form": form})
Enter fullscreen mode Exit fullscreen mode

Once these are done, you can style the form using django-crispy-forms. For now, that will be all.

Top comments (0)