-1

I have a problem i register site. I would like to make registartion panel and I would like to add When password and password confirmation are equal and not empty enable Register button After submit Form....But i really don't know how to do that. Could someone help me? Here is my code: signup.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <form method="post" action="{% url 'sign_upsucces' %}" >
        {% csrf_token %}

        {{ form }}

        {{ fail }}
        <button type = 'submit' {{ some }}>Zarejestruj się</button>

    </form>


</html>

views.py

def sign_upsucces(request):
    form = SignUpForm(request.POST or None)
    users = SignUp()
    people = SignUp.objects.all()
    fail = ''
    some = 'disabled'


    if form.is_valid():
        dane = form.save(commit=False)
        if (len(people)>0):
            try:
                person = SignUp.objects.get(login = dane.login)
            except SignUp.DoesNotExist:
                if dane.password == dane.password_confirm:
                    users.login = dane.login
                    users.password = dane.password
                    users.password_confirm = dane.password_confirm
                    users.save()
                    some = '<button type="submit">Zarejestruj się</button>'
                    fail = 'Konto utworzone!'
                    session = 'Zaloguj się'
                else:
                    fail = 'Hasła się nie zgadzają'
            else:
                fail = 'Istnieje'
                session = 'Zaloguj się'
        else:
            if dane.password == dane.password_confirm:
                user = SignUp()
                user.login = dane.login
                user.password = dane.password
                user.password_confirm = dane.password_confirm
                user.save()
                fail = 'Konto utworzone'
                session = 'Zaloguj się'




        return render(request, 'signup.html', {'form':form, 'dane':dane, 'fail':fail, 'some':some, 'session':session})

forms.py


class SignUpForm(ModelForm):
    class Meta:
        model = SignUp
        fields =['login','password','password_confirm']

models.py

from django.db import models

class SignUp(models.Model):

    login = models.CharField(max_length=100, blank = False, default="")
    password = models.CharField(max_length=100, blank=False)
    password_confirm = models.CharField(max_length=100, blank=False)

I would be very grateful for help. I have searched a lot but I can't find it. Thank You in advance!

Natalia

  • Do you want the registration button disabled (grayed out) and only when password1 and password2 match, the button becomes enabled / clickable? – Jarad Mar 04 '21 at 21:46

2 Answers2

0

You can create a custom clean method for the SignUpForm - see Cleaning a specific field attribute.

For the login field you have to create clean_login method and for password_confirm field clean_password_confirm method.

So you can do then something like the following.

forms.py:


from django.core.exceptions import ValidationError

from .models import SignUp

class SignUpForm(ModelForm):
    class Meta:
        model = SignUp
        fields =['login','password','password_confirm']

    def clean_login(self):
        login = self.cleaned_data.get("login")
        # Check SignUp Exists
        if SignUp.objects.filter(login=login).exists():
            raise ValidationError("The same login is exist!")
        return login

    def clean_password_confirm(self):
        password = self.cleaned_data.get("password")
        password_confirm = self.cleaned_data.get("password_confirm")
        # Verify passwords
        if password and password_confirm and password != password_confirm:
            raise ValidationError("Password mismatch!")
        return password_confirm

views.py:


def sign_upsucces(request):

    if request.method == 'POST':
        form = SignUpForm(request.POST)

        if form.is_valid():
            # Form is valid
            # So SignUp login is not exists
            # password confirmed and the same
            # With calling save() , You create an object
            signup_object = form.save()
            # Add here some messages for the user
    else:
        form = SignUpForm()

    return render(request, 'signup.html', {'form': form})

In HTML we can use form.as_p(), as_ul() or as_table() - see Outputting forms as HTML

.html:

<form method="post" action="{% url 'sign_upsucces' %}" >

    {% csrf_token %}

    {# RENDER FORM as a series of <p> tags. #}
    {# You will also see ther errors if form is not valid #}
    {{ form.as_p }}

    <button type='submit'>Zarejestruj się</button>

</form>
NKSM
  • 5,422
  • 4
  • 25
  • 38
-1

I an not sure if this can be done directly through django forms, but you can add custom javascript code to get the desired outcome.

In django forms all the input fields are assigned id based on their field name in models or forms as id_<field name> unless you specified explicitly. Keeping this in mind we can write custom js to enable/disable submit button.

You need to update your template as follows

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <form method="post" action="{% url 'sign_upsucces' %}" >
        {% csrf_token %}

        {{ form }}

        {{ fail }}
        <button type = 'submit' id="submit_button" disabled {{ some }}>Zarejestruj się</button>

    </form>
    <script>
        // create a list of id of items we will be attaching events to
        let items = ['id_password', 'id_password_confirm', 'submit_button']
        // get all items by id from items array
        let [password, password_confirm, button] = items.map((item) => document.getElementById(item))
        // add onkeyup eventlistener to all the input fields
        password.onkeyup = password_confirm.onkeyup = validator;

        // create validation function which will enable/disable submit button
        function validator(){
            button.disabled = !(password.value && (password.value === password_confirm.value))
        }
    </script>
</html>

in the above code i have accessed password fields and button by their id and wrote js code based on them. Check the comments in code to know more about how it works.

Note: I have added minimal validations i.e both password and password_confirm should be equal and not empty. Yo can extend this based on your need.

Hemant
  • 1,127
  • 1
  • 10
  • 18