0

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>
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
santosh Chauhan
  • 47
  • 2
  • 15
  • Does this answer your question? [Django Forms: if not valid, show form with error message](https://stackoverflow.com/questions/14647723/django-forms-if-not-valid-show-form-with-error-message) Also have a look at the documentation: https://docs.djangoproject.com/en/3.2/topics/forms/#rendering-fields-manually – Abdul Aziz Barkat Jun 09 '21 at 15:11
  • Hello, @AbdulAzizBarkat Does, you see my question and try to analyze the question or just refering the answer. I have searched all the answer. and the question which you refer it doesn;t help me... and One question is also asked in my above question is that. how to add email validation. You just close the answer thats it. – santosh Chauhan Jun 09 '21 at 15:26
  • I have read your question and that question does show you how to render the forms errors. Next "_One question is also asked in my above question_" you are **not** supposed to ask _multiple_ questions in one post, it should be one question per post. – Abdul Aziz Barkat Jun 09 '21 at 15:28
  • Hello @AbdulAzizBarkat, the above refer answer doesn;t help me. I try all the things but its like dump not displaying the error message. There is one more question asked in this above question is that."How to add code of email validation " in the same code – santosh Chauhan Jun 09 '21 at 15:29
  • Hello @AbdulAzizBarkat I will edit the code but you are closing the answer is not the solution – santosh Chauhan Jun 09 '21 at 15:30

1 Answers1

1

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.

Dean Elliott
  • 1,245
  • 1
  • 8
  • 12