from django import forms from django.contrib.auth.forms import PasswordChangeForm, UserCreationForm from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from captcha.fields import CaptchaField from .models import User class UserCreateForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" required_css_class = "field-required" password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password confirmation", widget=forms.PasswordInput ) class Meta: model = User fields = ["email", "first_name", "last_name"] def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserUpdateForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's disabled password hash display field. """ required_css_class = "field-required" password = ReadOnlyPasswordHashField() class Meta: model = User fields = [ "email", "password", "first_name", "last_name", 'shipping_street_address_1', 'shipping_street_address_2', 'shipping_city', 'shipping_state', 'shipping_postal_code', "is_active", "is_superuser" ] labels = { 'shipping_street_address_1': 'Street line 1', 'shipping_street_address_2': 'Street line 2', 'shipping_city': 'City', 'shipping_state': 'State', 'shipping_postal_code': 'ZIP code', } class CustomerUpdateForm(forms.ModelForm): class Meta: model = User fields = ( 'email', ) class CustomerShippingAddressUpdateForm(forms.ModelForm): class Meta: model = User fields = ( 'first_name', 'last_name', 'shipping_street_address_1', 'shipping_street_address_2', 'shipping_city', 'shipping_state', 'shipping_postal_code', ) labels = { 'shipping_street_address_1': 'Street line 1', 'shipping_street_address_2': 'Street line 2', 'shipping_city': 'City', 'shipping_state': 'State', 'shipping_postal_code': 'ZIP code', } class AccountCreateForm(UserCreationForm): required_css_class = "field-required" captcha = CaptchaField() class Meta: model = User fields = [ "email", "first_name", "last_name", ]