Removing help_text from Django UserCreateForm

隐身守侯 提交于 2019-11-28 08:19:07
Anurag Uniyal

You can set help_text of fields to None in __init__

from django.contrib.auth.forms import UserCreationForm
from django import forms

class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True)

    def __init__(self, *args, **kwargs):
        super(UserCreateForm, self).__init__(*args, **kwargs)

        for fieldname in ['username', 'password1', 'password2']:
            self.fields[fieldname].help_text = None

print UserCreateForm()

output:

<tr><th><label for="id_username">Username:</label></th><td><input id="id_username" type="text" name="username" maxlength="30" /></td></tr>
<tr><th><label for="id_password1">Password:</label></th><td><input type="password" name="password1" id="id_password1" /></td></tr>
<tr><th><label for="id_password2">Password confirmation:</label></th><td><input type="password" name="password2" id="id_password2" /></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr>

If you are doing too many changes, in such cases it is better to just override the fields e.g.

class UserCreateForm(UserCreationForm):
    password2 = forms.CharField(label=_("Whatever"), widget=MyPasswordInput 

but in your case my solution will work very well.

Another, cleaner option is to use help_texts dictionary in class Meta. Example:

class UserCreateForm(UserCreationForm):
    ...
    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")
        help_texts = {
            'username': None,
            'email': None,
        }

More info in here: https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#overriding-the-default-fields

Works perfect for username and email, but doesn't work for password2. No idea why.

You can add css class to registration_form.html file like this.

<style>

.helptext{
  visibility: hidden;
}

</style>

Simple CSS solution.

<style>
     #hint_id_username, #hint_id_password1 {
         display: none;
     }
</style>

When the forms render inspect the page source code and you will see an id for each help text. Such as hint_id_username for each form field. Use the above CSS to hide the text.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!