form errors

Date: April 21st 2016
Last updated: April 21st 2016

I made several changes to my App and later realised that my crispy form was no longer rendering errors when a form was not validated. Why? The way I found the problem was by printing form.errors.

My RegistrationForm has two forms associated with two models; User and Surfer.

views.py (RegistrationForm)

def register_user(request):
    logout(request)
    if request.method == 'POST':
        user_form = MyRegistrationForm(data=request.POST, prefix='form1')
        # NOTE: SurferForm would NOT validate without specifying data=request.POST
        # instead of simply 'request.POST'
        profile_form = SurferForm(data=request.POST or None, prefix='form2')

        # ORIGINAL CODE
        #if all((user_form.is_valid(), profile_form.is_valid())):

        # MODIFIED TO...
        print(user_form.errors) #<======== PRINTS TO CONSOLE 
        # In my case the form wouldn't validate because a user already existed with the username 
          # that I was trying to register
        a_valid=user_form.is_valid()
        b_valid=profile_form.is_valid()

        # Checkpoint to see which form is failing
        print(a_valid)
        print(b_valid)
        if a_valid and b_valid:
            # ORIGINAL CODE
            userid = user_form.save()
            profile = profile_form.save(commit=False)
            profile.user = userid
            profile.save()
            # authenticate the new user
            new_user = authenticate(username=user_form.cleaned_data['username'],
                                    password=user_form.cleaned_data['password1'],)
            login(request, new_user)
            return redirect('/{}/'.format(profile.id))

    # ORIGINAL CODE
    # NOTE: The reason I lost my error messages was becuase my original code would render a
    # completely new form with empty fields when a form did not validate. No error messages 
    # are available to the new empty form 
    #args = {}
    #args.update(csrf(request))
    #args['form'] = MyRegistrationForm(prefix='form1')
    #args['profileform'] = SurferForm(prefix='form2')

    # MODIFIED TO...
    else:
        user_form = MyRegistrationForm(prefix='form1')
        profile_form = SurferForm(prefix='form2')
    data = { 'user_form': user_form, 'profile_form': profile_form }

    return render(request, 'surferprofile/register.html', data)#args)

results matching ""

    No results matching ""