[Python] Django forms.py and Join.html not rendering form errors

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024.

  1. Stack

    Stack Membro Participativo

    I have seen many tutorials on this, (I am new to Django) and the only issue I could find was raise form.Validation("...") was not rendering on my HTML template and did not stop the form from submitting.

    I tried many options including AI yet I was still running into the same problems. If I have made a silly mistake please point it out so I know for next time, this code is just a project of mine so I can learn how to code Django.

    HTML:

    <form id="form" action="" method="post" name="form">
    {% csrf_token %}
    <div class="input-control">
    {% if form.non_field_errors %}
    <div class="error">{{ form.non_field_errors }}</div>
    {% endif %}

    {% if form.errors %}
    <div class="error">{{ form.errors }}</div>
    {% endif %}

    <div class="username">
    <label for="{{ form.username.id_for_label }}" class="label">{{ form.username.label }}</label>
    {{ form.username }} <!-- Render the input field -->
    {% for error in form.username.errors %}
    <div class="error">{{ error }}</div>
    {% endfor %}
    </div>

    <div class="email">
    <label for="{{ form.email.id_for_label }}" class="lemail">{{ form.email.label }}</label>
    {{ form.email }}
    {% for error in form.email.errors %}
    <div class="error">{{ error }}</div>
    {% endfor %}
    </div>

    <div class="password">
    <label for="{{ form.password.id_for_label }}" class="label">{{ form.password.label }}</label>
    {{ form.password }}
    {% for error in form.password.errors %}
    <div class="error">{{ error }}</div>
    {% endfor %}
    </div>

    <div class="repassword">
    <label for="{{ form.repassword.id_for_label }}" class="label">{{ form.repassword.label }}</label>
    {{ form.repassword }}
    {% for error in form.repassword.errors %}
    <div class="error">{{ error }}</div>
    {% endfor %}
    </div>

    <button id="nextButton" class="nextButton" type="submit">
    <span class="material-symbols-outlined">arrow_circle_right</span>
    </button>
    </div>
    </form>


    Forms.py:


    from django import forms
    from django.contrib.auth.models import User

    class JoinForm(forms.Form):
    username = forms.CharField(
    validators=['clean_username'],
    widget=forms.TextInput(attrs={
    'id': "usernameId",
    'name': "username",
    'type': "text",
    'placeholder': "username",
    'autocomplete': "username",
    'maxlength': 64,
    'required': True,
    }),
    label='Username'
    )
    email = forms.EmailField(
    validators=['clean_email'],
    widget=forms.EmailInput(attrs={
    'id': "emailId",
    'name': "email",
    'type': "text",
    'placeholder': "email" ,
    'autocomplete': "email",
    'maxlength': 256,
    'required': True,
    }),
    label='Email'
    )
    password = forms.CharField(
    validators=['clean_password'],
    widget=forms.PasswordInput(attrs={
    'id': "passwordId",
    'name': "password",
    'type': "password",
    'placeholder': "password",
    'autocomplete': "new-password",
    'maxlength': 127,
    'required': True,
    }),
    label='Password'
    )
    repassword = forms.CharField(
    validators=['clean_repassword'],
    widget=forms.PasswordInput(attrs={
    'id': "repasswordId",
    'name': "repassword",
    'type': "password",
    'placeholder': "re-confirm password",
    'maxlength': 127,
    'required': True,
    }),
    label='Password'
    )

    def clean_username(self):
    print("Cleaning username")
    username = self.cleaned_data.get('username')
    if username and User.objects.filter(username=username).exists():
    raise forms.ValidationError("Username already exists.")
    return username

    def clean_email(self):
    print("Cleaning email")
    email = self.cleaned_data.get('email')
    if email and '@example.com' in email:
    raise forms.ValidationError("Email from example.com is not allowed.")
    elif email and User.objects.filter(email=email).exists():
    raise forms.ValidationError("Email already exists.")
    return email

    def clean_password(self):
    print("Cleaning password")
    password = self.cleaned_data.get('password')
    if password and len(password) < 8:
    raise forms.ValidationError("Password must be at least 8 characters")
    return password

    def clean_repassword(self):
    print("Cleaning repassword")
    repassword = self.cleaned_data.get('repassword')
    password = self.cleaned_data.get('password')
    if repassword != password:
    raise forms.ValidationError("Passwords do not match")
    return repassword




    views.py:


    from django.shortcuts import render, redirect
    from .forms import JoinForm
    from django.contrib.auth import login, logout
    from django.http import HttpResponse, HttpRequest, HttpResponseRedirect, JsonResponse
    from django.contrib.auth.models import User
    from django.contrib.auth.views import LogoutView, LoginView
    from django.urls import reverse_lazy
    import json


    def index(request):
    return render(request, 'Index.html')

    def create_user(request):
    # if User.objects.exists():
    # return redirect('index')
    if request.method == 'POST':
    form = JoinForm(request.POST)
    if form.is_valid():
    # Extract cleaned data
    username = form.cleaned_data['username']
    password = form.cleaned_data['password']
    email = form.cleaned_data['email']

    # Create the user
    user = User.objects.create_user(username=username, password=password, email=email)
    user.save()

    # Log the user in
    login(request, user)

    # Redirect to success page
    return redirect('send_call')
    else:
    return redirect('create_user')
    else:
    form = JoinForm()

    # For GET requests, render the Join.html page
    return render(request, 'Join.html', {'form': form})

    Continue reading...

Compartilhe esta Página