santosh Chauhan
santosh Chauhan

Reputation: 77

Template not displaying Validation error (Django)

I'm trying to display the Validation Error in my template (register.html) but it's not displaying. What is wrong with this code?

and one more question "how I can display email already exist in this form"

I don't know how to display the "email already exist".

The Codes Goes here.

forms.py

from django.contrib.auth.models import User
from django import forms
from .models import *
from django.utils.translation import gettext as _


class RegisterForm(forms.ModelForm):
    username = forms.CharField(widget=forms.TextInput())
    password = forms.CharField(widget=forms.PasswordInput())
    email = forms.CharField(widget=forms.EmailInput())

    class Meta:
        model = Customer
        fields =["full_name", "username", "email", "password"]

    def clean_username(self):
        uname = self.cleaned_data.get('username')
        if User.objects.filter(username = uname).exists():
            raise forms.ValidationError(_('Customer with this username already exists'), code='invalid')

        return uname

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
        self.fields['username'].widget.attrs['style'] = 'width:500px; height:40px;'
        self.fields['password'].widget.attrs['style']  = 'width:500px; height:40px;'
        self.fields['email'].widget.attrs['style']  = 'width:500px; height:40px;'
        self.fields['full_name'].widget.attrs['style']  = 'width:500px; height:40px;'

I can't display the Error Message on above code Customer with this username already exists

views.py

from django.shortcuts import render, redirect
from django.views.generic import CreateView, View, FormView
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse_lazy
from .forms import *
# Create your views here.
class customerRegister(CreateView):
    template_name = "register.html"
    form_class = RegisterForm
    success_url = reverse_lazy("main_app:base")
    def form_valid(self, form):
        username = form.cleaned_data.get("username")
        email = form.cleaned_data.get("email")
        password = form.cleaned_data.get("password")     
        user = User.objects.create_user(username, email, password)
        form.instance.user = user
        login(self.request, user)
        return super().form_valid(form)
    def get_success_url(self):
        if "next" in self.request.GET:
            next_url = self.request.GET.get("next")
            return next_url
        else:
            return self.success_url
    

register.html

<body style="background-color: #95a5a6">
  {% if error %}
  <div class="alert alert-dismissible alert-danger">
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    <strong>Oh snap!</strong>{{form.non_field_errors}}
  </div>
  {% endif %}
  <div class="container-register mx-auto">
    <form action="{% url 'account:register' %}" method="post">
      {% csrf_token %}
      <fieldset>
        <h2 class="text-center" style="margin-top: 50px">Register</h2>
        <div class="form-group">
          <label class="col-form-label mt-4" for="inputDefault">Full Name*</label><br>
          {{form.full_name}}<br>
        </div>
        <div class="form-group">
          <label class="col-form-label mt-4" for="inputDefault">Username*</label><br>
          {{form.username}}<br>
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1" class="form-label mt-4 ">Email address*</label><br>
          {{form.email}}<br>
          <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
        </div>
        <div class="form-group">
          <label for="exampleInputPassword1" class="form-label mt-4">Password*</label><br>
          {{form.password}}<br>
        </div>
        <br/>
        <div class="text-center">
        <button type="submit" class="btn btn-lg btn-primary">Register</button>
        </div>
      </fieldset>
  </form>
    <hr>  
    <h5 class="text-center" style="margin-top: 50px">Already Registered?<a class="nav-link" href="{% url 'account:login'%}">Log in</a></h5>
  </div>
</body>

Upvotes: 0

Views: 1406

Answers (1)

Dean Elliott
Dean Elliott

Reputation: 1323

In your template you have {% if error %} which does not exist as you are not passing the template context error. Inside the template if you are then accessing {{form.non_field_errors}} which will exist if there are errors.

So it should be {% if form.non_field_errors %} like so:

  {% if form.non_field_errors %}
  <div class="alert alert-dismissible alert-danger">
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    <strong>Oh snap!</strong>{{form.non_field_errors}}
  </div>
  {% endif %}

See related StackOverflow post here for customising the email error message.

Upvotes: 1

Related Questions