0

I am having troubles handling errors in my signup form particularly with password1 & 2 validation, existing username & email handling. Here is my form:

class RegisterForm(UserCreationForm):
    class Meta():
        model = User
        fields = ('username', 'email', 'password1', 'password2')
        widgets = {
            'username': forms.TextInput(attrs={'class':  'form-control', 'name':'username' }),
            'email': forms.EmailInput(attrs={'class':  'form-control' }),
        }

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.fields['password1'].widget = forms.PasswordInput(attrs={'class': 'form-control', 'name':'password'})
        self.fields['password2'].widget = forms.PasswordInput(attrs={'class': 'form-control'})

class UserProfileForm(forms.ModelForm):
        class Meta():
            model = UserProfile
            fields = ('location', 'favourite_activity')
            widgets = {
                'favourite_team': forms.TextInput(attrs={'class':  'form-control' }),
            }

Here is my views.py:

def registerView(request):
    regForm = RegisterForm()
    proForm = UserProfileForm()
    
    if request.method == 'POST':
        regForm = RegisterForm(request.POST)
        proForm = UserProfileForm(request.POST)
        
    if regForm.is_valid() and proForm.is_valid():
        user = regForm.save(commit=True)
        profile = proForm.save(commit=False)
        profile.user = user
        profile.save()
    
        username = request.POST.get('username')
        password = request.POST.get('password1')

        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                return redirect ('timeline')
        else:
            return HttpResponse("There was a problem signing you up!")

    regDic = {'regForm': regForm, 'proForm': proForm}
    return render(request, 'person/register.html', context=regDic)

And finaly the template file:

<form method="POST">
  {% csrf_token %}
  <div class="form-group">
    <label>{{ regForm.username.label }}</label>
    {{ regForm.username }}          
  </div>

  <div class="form-group">
    <label>Email address</label>
    {{ regForm.email }}
  </div>

  <div class="form-group">
    <div class="d-flex justify-content-between mg-b-5">
      <label class="mg-b-0-f">Password</label>
    </div>
    {{ regForm.password1 }}
  </div>
  <div class="form-group">
    <div class="d-flex justify-content-between mg-b-5">
       <label class="mg-b-0-f">Confirm Password</label>
    </div>
    {{ regForm.password2 }}
  </div>
  <div class="form-group">
    <div class="d-flex justify-content-between mg-b-5">
      <label class="mg-b-0-f">Favourite Team</label>
    </div>
    {{ proForm.favourite_team }}
  </div>
  <div class="form-group tx-12">
              By clicking <strong>Create an account</strong> below, you agree to our terms of service and privacy statement.
  </div><!-- form-group -->
  <input type="submit" value="Create Account">
              
  <!-- <button type="submit" class="btn btn-brand-02 btn-block">Create Account</button> -->
</form>

<div class="divider-text">or</div>
  <button class="btn btn-outline-facebook btn-block">Sign Up With Facebook</button>
  <button class="btn btn-outline-twitter btn-block">Sign Up With Twitter</button>
<div class="tx-13 mg-t-20 tx-center">Already have an account? <a href="{% url 'person:login' %}">Sign In</a></div>
</div>
  {{ regForm.errors }}
  {{ proForm.errors }}
</div>

Everything works fine, I could authenticate the user as they sign up, log them in and redirect them but if there is an error in the signup form then I can't get the user to understand which field is responsible and correct it before they submit.

Any idea how to ensure display password1 & password2 mismatch error, existing username and existing email error in the sign up page? I am out of ideas.

crimsonpython24
  • 2,223
  • 2
  • 11
  • 27
Paschal
  • 725
  • 1
  • 9
  • 17

1 Answers1

0

You can simply specify custm error message, like this:

class RegisterForm(UserCreationForm):
    username = forms.CharField(error_messages={'required': 'error message here'})

    class Meta:
        model = User

And yes, if you already have the username field in your meta class, I believe this only overrides the default field and will not create a duplicate.

If you want further customization, you can do this:

username_errors = {
    'required': 'This field is required',
    'invalid': 'Enter a valid value'
}

class RegisterForm(UserCreationForm):
    username = forms.CharField(error_messages=username_errors)
    # ... and don't forget your Meta class

Documentation, reference #1, and reference #2.

crimsonpython24
  • 2,223
  • 2
  • 11
  • 27