How I can return the email again to the form if the login is invalid

Viewed 51

How I can return the register information again to the register Form if the email not valid because as default if the email invalid the form are resitting

def register_view(request, *args, **kwargs):
    user = request.user
    if user.is_authenticated:
        return HttpResponse("You are already authenticated as " + str(user.email))

    context = {}
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            email = form.cleaned_data.get('email').lower()
            raw_password = form.cleaned_data.get('password1')
            account = authenticate(email=email, password=raw_password)
            login(request, account)
            destination = kwargs.get("next")
            if destination:
                return redirect(destination)
            return redirect('home')
        else:
            context['registration_form'] = form

    else:
        form = RegistrationForm()
        context['registration_form'] = form
    return render(request, 'account/my login/register.html', context)
1 Answers

if the form is invalid send the form back with the data in your request. For example in your form validation else statement should be something like this:

return render(request, 'account/my login/register.html',{'form':form})

If you want to send only the email field back then clean the other fields in the form except for the email and send only the email data back.

        if form.is_valid():
                # form validation logic here
        else:
            return render(request, 'account/my login/register.html',{'form':form})
Related