Reputation: 1106
I am struggling with changing default UserCreationForm - I was able to add one additional field by creating child class:
class SignUpForm(UserCreationForm):
display_name = forms.CharField(max_length=32, help_text='Your display name')
class Meta:
model = User
fields = ('username', 'display_name', 'password1', 'password2', )
def register(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.profile.display_name = form.cleaned_data.get('display_name')
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('user/home')
else:
form = SignUpForm()
return header.views.show(request, 'userpanel/register.html', context={'form': form})
Together with template:
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text | safe }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error | safe }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Sign up</button>
</form>
I was able to create following page:
But I have the problem with changing description texts on a page. Now, if I would like to change Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. to something else, how to do it?
Upvotes: 3
Views: 2406
Reputation: 1106
Okay, I figured it out. Listing all properties of a form by:
form = SignUpForm()
for d in dir(form):
print(d)
I found, by trials and errors, that you can list fields of the form:
form = SignUpForm()
for d in form.fields:
print('field name:', d)
print('field label:', form.fields[d].label)
print('field text:', form.fields[d].help_text)
print("")
returns:
field name: username
field label: Username
field text: Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.
field name: display_name
field label: None
field text: Your display name
field name: password1
field label: Password
field text: <ul><li>Your password can't be too similar to your other personal information.</li><li>Your password mus
t contain at least 8 characters.</li><li>Your password can't be a commonly used password.</li><li>Your password can&
#39;t be entirely numeric.</li></ul>
field name: password2
field label: Password confirmation
field text: Enter the same password as before, for verification.
I can easily alter those fields by writting:
x = form.fields['username']
x.label = "foo"
x.help_text = "bar"
and I got:
Upvotes: 3