Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage UserCreationForm properties and fields

I am new in Django and even after trying thoroughly to find an answer for this question, I couldn't find any. =/

I am using UserCretionForm to create my users and I wanted to know a couple of things:

1 - How can I manage this form's properties? (e.g. I don't want to show the tips like "Required. 30 charact..." or "Enter the same password as above, for verification.")

2 - I want to make it show other customized fields. How can I do it? (please, try to be clear where I have to write the codes you'll show me as I am not an expert =D ). (e.g. Here in Brazil we have some national info I need to store. That is why I need these fields.)

Thanks in advance! (Y)

like image 991
Lucas Rezende Avatar asked Dec 24 '11 02:12

Lucas Rezende


People also ask

What is UserCreationForm in Django?

Django UserCreationForm is used for creating a new user that can use our web application. It has three fields: username, password1, and password2(which is basically used for password confirmation). To use the UserCreationForm, we need to import it from django.


1 Answers

Changing the default validator messages

You can change the error messages for the default validators via the error_messages argument to a form field.

To find out which validators exist per field, check here: https://docs.djangoproject.com/en/dev/ref/forms/fields/#built-in-field-classes

class MyForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['username'].error_messages = {'invalid': 'foobar'}
        self.fields['password1'].error_messages = {'required': 'required, man'}

Adding new fields to an existing form

If you want to add new fields, you'd add them via subclassing (which is just python).

If you subclass UserCreationForm and add a field to it, you end up with a new form class that simply has the original's fields and your new ones.

class MyForm(UserCreationForm):
    extra_field = forms.CharField()

Overriding the admin form

If you are trying to override the UserCreationForm that the admin site uses by default, you'll have to register a new ModelAdmin for the User moder.

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from foo import MyNewUserCreationForm

class NewUserAdmin(UserAdmin):
    add_form = MyNewUserCreationForm

admin.site.unregister(User)
admin.site.register(User, NewUserAdmin)
like image 81
Yuji 'Tomita' Tomita Avatar answered Sep 21 '22 00:09

Yuji 'Tomita' Tomita