Configuring UserCreationForm for an email address as a username in Django 1.2

Django 1.2 adds new valid characters to usernames, which means that usernames can simply be email addresses. So far I have used the built-in UserCreationForm to register - how can I change it to mark the "username" field the "email" field? And how to add additional (but still User objects) fields such as first name and last name? (And how to make them optional?)

Should I change in UserCreationForm to such an extent, or is it better to start from scratch (and if the latter, how?)

Thanks.

+4
source share
1 answer

To change the email field label, you can subclass UserCreationForm as follows

 from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.forms import UserCreationForm class MyUserCreationForm(UserCreationForm): username = forms.RegexField(label=_("Email"), max_length=30, regex=r'^[\ w.@ +-]+$', help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."), error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")}) 

Adding the first_name and last_name fields is not so simple because the form save method accepts only a username, email address and password. Two possibilities are possible:

  • override form save method
  • displays the UserChangeForm after creating the User (this is what the Django admin application does)
+2
source

Source: https://habr.com/ru/post/1316625/


All Articles