I have been trying for weeks to see how I return validation errors defined in my forms.py and pass it to Ajax, I saw a couple of solutions online and thier Django versions are either too old or the Django and JS codes are too complicated. I want someone to help me out using code samples to demonstrate how this is achievable. I want both error messages coming from Django to displayed in my webpage as well as success message. Below is what I have done so far.
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Email already exists.")
return email
def clean(self):
cleaned_data = super().clean()
email = cleaned_data.get('email')
vmail = cleaned_data.get('vemail')
if email != vmail:
raise forms.ValidationError('Your first email and second email must match')
elif not email.endswith('@alabiansolutions.com'):
raise forms.ValidationError('Please we need alabiansolution email')
views.py
from django.shortcuts import render
from django.views.generic import ListView, View, CreateView
from ajax_app.forms import UserCreateForm
from django.urls import reverse_lazy
# Create your views here.
def user_create_view(request):
if request.method == 'POST':
user_form = UserCreateForm(request.POST)
if user_form.is_valid():
user_form.save()
else:
user_form = UserCreateForm()
return render(request, 'ajax_app/index.html', {'user_create_form':user_form})
urls.py
from django.contrib import admin
from django.urls import path
from ajax_app import views
urlpatterns = [
path('', views.user_create_view, name='user_create_view'),
]
index.html
{% if user_create_form.non_field_errors %}
<div class="well well-error">
{% for error in user_create_form.non_field_errors %}
<ul class="list-unstyled">
<li class="text-danger">
<i class="fa fa-exclamation-circle" aria-hidden="true"></i>
<strong> {{ error|escape }}</strong>
</li>
</ul>
{% endfor %}
</div>
{% endif %}
<h3>Add Data</h3>
<form id="addUser" action="{% url 'user_create_view' %}" method="POST">
<table>
{{ user_create_form.as_table}}
</table>
{% csrf_token %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
script.js
// Create Django Ajax Call
$("form#addUser").submit(function() {
var form = $("#addUser");
// Create Ajax Call
$.ajax({
url: form.attr("action"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
// I don't know next step
}
});
$('form#addUser').trigger("reset");
return false;
});