Question

I was building a login/logout User system with django, and I started playing around with the django auth system.

I am using the custom Django UserCreationForm like so:

views.py

from django.contrib.auth.forms import UserCreationForm

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST) 
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/books/")
    else:
        form = UserCreationForm()
    return render(request, "registration/register.html", {
        'form': form,
    })

But this form renders a lot of unwanted stuff, as shown here: https://app.box.com/s/wmrtyal3mctb9hctsnom

First, I would like to get rid of the added information, is there a good way to do this? Are there any good ways to do this? Is there a way to edit the UserCreationForm myself or would I have to create my own form?

Second, lets assume I want to add more required fields to a registration page, what is the best way to do this? Say I wanted to make it the case that a person register male or female -I realize I should extend the user model, but how would I register both to the original user model and the extended user model?

Was it helpful?

Solution

Rather than extend the UserCreationForm class, you should rewrite it. Check out the source for it here.

For example, if you wanted to get rid of the text next to the password field that says 'Enter the same password as above', remove this line:

help_text=_("Enter the same password as above, for verification."))

from django /django/contrib/auth/forms.py (in the link above)


EDIT: The reason I suggested that you rewrite the forms classes rather than extending them is because it is simply more convenient this way. From the Django docs:

If you don’t want to use the built-in views, but want the convenience of not having to write forms for this functionality, the authentication system provides several built-in forms located in django.contrib.auth.forms

If you were to extend your User model classes you would need to change the form classes accordingly. Again from the docs:

As you may expect, built-in Django’s forms and views make certain assumptions about the user model that they are working with. If your user model doesn’t follow the same assumptions, it may be necessary to define a replacement form, and pass that form in as part of the configuration of the auth views.

See here and here for more details

If you simply want to change the UserCreationForm you would edit the UserCreationForm class as in the forms.py module as I mentioned above.

If, as you mentioned in your question, you want to add more required fields to a registration page, you would need to make a custom User model. See here for details on how to do this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top