How should I display the error messages on the HTML template, for Example I write a condition in the forms.py that if username already exist in the database, it should display the message on the HTML page, How should I do this? Following is my code:
View.py
from django.shortcuts import render,redirect
from django.views.generic import View,TemplateView
from .forms import Registration_Form
from .models import User_Registration
from django.contrib import messages
# Create your views here.
class MainPageView(TemplateView):
template_name='main.html'
class LoginView(TemplateView):
template_name='login.html'
def RegistrationView(request):
form=Registration_Form()
if request.method=='POST':
form=Registration_Form(request.POST)
if form.is_valid():
user_name=form.cleaned_data['username']
print(User_Registration.objects.filter(username=user_name))
form.save()
return redirect('login_view')
else:
# messages.error(request,"Form is Invalid!")
return redirect('registration_view')
else:
return render(request,'registration.html',{'form':form})
# template_name='registration.html'
forms.py
from django import forms
from .models import User_Registration
class Registration_Form(forms.ModelForm):
class Meta:
model=User_Registration
fields=('company_name','username','password','email')
widgets={
'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}),
'username':forms.TextInput(attrs={'class':'form-control'}),
'password':forms.PasswordInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
}
def clean(self):
user_name=self.cleaned_data['username']
if User_Registration.objects.filter(username=user_name).exists():
raise forms.ValidationError("Username Already Exist")