Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django UserCreationForm with one password

I'm wondering if I could make UseCreationForm without password confirmation (only password1). Code I'm working with:

#forms.py
class UserRegistrationForm(UserCreationForm):
    email = forms.EmailField(max_length=200, help_text='Required')

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

#views.py
class HomeView(View):
    template_name = 'home.html'

    def get(self, request):
        queryset = Profile.objects.filter(verified=True)
        form = UserRegistrationForm()
        context = {
            'object_list': queryset,
            'form':form,
            'num_of_users': User.objects.all().count()
        }
        return render(request, self.template_name, context)

The problem is, that when I make forms.py as that:

class UserRegistrationForm(UserCreationForm):
    email = forms.EmailField(max_length=200, help_text='Required')

    class Meta:
        model = User
        fields = ('username', 'email', 'password1')

Form has also field password2. Any solution of that?

like image 803
Barburka Avatar asked Aug 08 '17 13:08

Barburka


1 Answers

You can override the __init__() method of your form and remove the field you want:

class UserRegistrationForm(UserCreationForm):
    email = forms.EmailField(max_length=200, help_text='Required')

    class Meta:
        model = User
        fields = ('username', 'email', 'password1')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        del self.fields['password2']

Important: Anyway, it is not a common practice to have only one field for password, because user can mistype it. And security level decreases a lot.

like image 130
wencakisa Avatar answered Oct 15 '22 02:10

wencakisa