Manage UserCreationForm properties and fields
Asked Answered
C

1

7

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)

Cispadane answered 24/12, 2011 at 2:25 Comment(0)
O
12

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)
Orate answered 24/12, 2011 at 8:40 Comment(2)
Hey Yuji, thanks for your reply. I just have one doubt left. Where do I have to do that? ThanksCispadane
@user1072627 Do what? Wherever your form is defined... if you're talking about the admin, you just need to put that somewhere that is run by django, so for example you could make a "patch" app and add it to INSTALLED_APPS, then put the admin form code in admin.py assuming you have admin.autodiscover() in your urls.py.Broadbrim

© 2022 - 2024 — McMap. All rights reserved.