Using jquery POST request to save form in django
Question:
here my form.html in this form I’m use Django model form.
<div class="container">
<form action="{% url 'add_product' %}" id="product_form" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-sm-12">
<label for="">{{form.code.label}} :</label>
{{form.code}}
<span id="error">{{form.code.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.company_id.label}} :</label>
{{form.company_id}}
<span id="error">{{form.company_id.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.item_id.label}} :</label>
{{form.item_id}}
<span id="error">{{form.item_id.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.name.label}} :</label>
{{form.name}}
<span id="error">{{form.name.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.price.label}} :</label>
{{form.price}}
<span id="error">{{form.price.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.pro_image.label}}</label>
{{form.pro_image}}
<p style="color:red">{{form.pro_image.help_text}}</p>
<span id="error">{{form.pro_image.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.desc.label}}</label>
{{form.media}}
{{form.desc}}
<span id="error">{{form.desc.errors | striptags }}</span>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label for="">{{form.status.label}}</label>
{{form.status}}
<span id="error">{{form.status.errors | striptags }}</span>
</div>
</div>
<div class="row">
<div class="col-sm-4 mt-2 mb-2">
<button type="submit" class="btn btn-success">
<i class="{{btn_type}}"></i>
</button>
<a href="{% url 'product' %}">
<button type="button" class="btn btn-primary"><i class="fa fa-long-arrow-alt-left"></i></button>
</a>
</div>
</div>
</form>
{% if img_object %}
<img src="{{ img_object.pro_image.url}}" alt="connect" style="max-height:300px">
{% endif %}
</div>
**jQuery code I can’t find the error because browser status=200 but when I’m check the Django terminal it’s showing error. jQuery serialize Django support or not ?? **
var frm = $('#product_form');
frm.submit(function(){
$.ajax({
type:frm.attr('method'),
headers: { "X-CSRFToken": '{{ csrf_token }}' },
url:frm.attr('action'),
data:frm.serialize(),
contentType: 'multipart/form-data',
processData: false,
contentType: false,
success:function(data){
$('#msg').html(data)
},
else:function(data){
$('#msg').html(data)
}
});
return false;
});
**here my views.py please guide if do any wrong. **
def Add_Product(request):
# noti,msg = Notificatino()
if request.method == "POST":
form = ProductForm(request.POST, request.FILES)
print("testing")
try:
if form.is_valid:
forms = form.save(commit=False)
forms.create_by=request.user
forms.save()
form = ProductForm()
messages.success(request,'Product Has been added.')
#return redirect('product')
except:
print(str(form.errors))
messages.error(request, str(form.errors))
else:
form = ProductForm()
context={
# 'noti':noti,
'form':form,
'title':'iPanel | Product Master',
'page_title':'Product List',
'tree_title_1':'Product',
'tree_title_2':'Add',
'tree_url':'product',
'btn_type':'fa fa-regular fa-plus',
}
return render(request,'panel/product/form.html',context)
Error while sending the post request
<ul class="errorlist"><li>company_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>item_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>name<ul class="errorlist"><li>This field is required.</li></ul></li><li>price<ul class="errorlist"><li>This field is required.</li></ul></li><li>pro_image<ul class="errorlist"><li>This field is required.</li></ul></li><li>status<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Answers:
At first, it should be form.is_valid()
not only form.is_valid
, it is method not property and secondly, you should not intialise the empty form inside the if block of is_valid()
so:
def Add_Product(request):
# noti,msg = Notificatino()
if request.method == "POST":
form = ProductForm(request.POST, request.FILES)
print("testing")
try:
if form.is_valid():
forms = form.save(commit=False)
forms.create_by=request.user
forms.save()
messages.success(request,'Product Has been added.')
return redirect('product')
except:
print(str(form.errors))
messages.error(request, str(form.errors))
else:
form = ProductForm()
context={
# 'noti':noti,
'form':form,
'title':'iPanel | Product Master',
'page_title':'Product List',
'tree_title_1':'Product',
'tree_title_2':'Add',
'tree_url':'product',
'btn_type':'fa fa-regular fa-plus',
}
return render(request,'panel/product/form.html',context)
It seems like the issue is with the validation of the form fields in the Django view. The error message suggests that some fields are required but are not being passed in the POST request.
In your jQuery code, you are serializing the form data and sending it as the data parameter in the AJAX call. However, since you are using enctype="multipart/form-data"
in your HTML form, you cannot simply use serialize()
method to serialize
the form data. Instead, you can use the FormData()
constructor to create a new FormData object and append the form fields to it.
Here’s how you can modify your jQuery
code:
var frm = $('#product_form');
frm.submit(function(e){
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
type:frm.attr('method'),
headers: { "X-CSRFToken": '{{ csrf_token }}' },
url:frm.attr('action'),
data:form_data,
contentType: false,
processData: false,
success:function(data){
$('#msg').html(data)
},
error:function(data){
$('#msg').html(data.responseText)
}
});
});
Read this article for more information
here my form.html in this form I’m use Django model form.
<div class="container">
<form action="{% url 'add_product' %}" id="product_form" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-sm-12">
<label for="">{{form.code.label}} :</label>
{{form.code}}
<span id="error">{{form.code.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.company_id.label}} :</label>
{{form.company_id}}
<span id="error">{{form.company_id.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.item_id.label}} :</label>
{{form.item_id}}
<span id="error">{{form.item_id.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.name.label}} :</label>
{{form.name}}
<span id="error">{{form.name.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.price.label}} :</label>
{{form.price}}
<span id="error">{{form.price.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.pro_image.label}}</label>
{{form.pro_image}}
<p style="color:red">{{form.pro_image.help_text}}</p>
<span id="error">{{form.pro_image.errors | striptags }}</span>
</div>
<div class="col-sm-12">
<label for="">{{form.desc.label}}</label>
{{form.media}}
{{form.desc}}
<span id="error">{{form.desc.errors | striptags }}</span>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label for="">{{form.status.label}}</label>
{{form.status}}
<span id="error">{{form.status.errors | striptags }}</span>
</div>
</div>
<div class="row">
<div class="col-sm-4 mt-2 mb-2">
<button type="submit" class="btn btn-success">
<i class="{{btn_type}}"></i>
</button>
<a href="{% url 'product' %}">
<button type="button" class="btn btn-primary"><i class="fa fa-long-arrow-alt-left"></i></button>
</a>
</div>
</div>
</form>
{% if img_object %}
<img src="{{ img_object.pro_image.url}}" alt="connect" style="max-height:300px">
{% endif %}
</div>
**jQuery code I can’t find the error because browser status=200 but when I’m check the Django terminal it’s showing error. jQuery serialize Django support or not ?? **
var frm = $('#product_form');
frm.submit(function(){
$.ajax({
type:frm.attr('method'),
headers: { "X-CSRFToken": '{{ csrf_token }}' },
url:frm.attr('action'),
data:frm.serialize(),
contentType: 'multipart/form-data',
processData: false,
contentType: false,
success:function(data){
$('#msg').html(data)
},
else:function(data){
$('#msg').html(data)
}
});
return false;
});
**here my views.py please guide if do any wrong. **
def Add_Product(request):
# noti,msg = Notificatino()
if request.method == "POST":
form = ProductForm(request.POST, request.FILES)
print("testing")
try:
if form.is_valid:
forms = form.save(commit=False)
forms.create_by=request.user
forms.save()
form = ProductForm()
messages.success(request,'Product Has been added.')
#return redirect('product')
except:
print(str(form.errors))
messages.error(request, str(form.errors))
else:
form = ProductForm()
context={
# 'noti':noti,
'form':form,
'title':'iPanel | Product Master',
'page_title':'Product List',
'tree_title_1':'Product',
'tree_title_2':'Add',
'tree_url':'product',
'btn_type':'fa fa-regular fa-plus',
}
return render(request,'panel/product/form.html',context)
Error while sending the post request
<ul class="errorlist"><li>company_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>item_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>name<ul class="errorlist"><li>This field is required.</li></ul></li><li>price<ul class="errorlist"><li>This field is required.</li></ul></li><li>pro_image<ul class="errorlist"><li>This field is required.</li></ul></li><li>status<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
At first, it should be form.is_valid()
not only form.is_valid
, it is method not property and secondly, you should not intialise the empty form inside the if block of is_valid()
so:
def Add_Product(request):
# noti,msg = Notificatino()
if request.method == "POST":
form = ProductForm(request.POST, request.FILES)
print("testing")
try:
if form.is_valid():
forms = form.save(commit=False)
forms.create_by=request.user
forms.save()
messages.success(request,'Product Has been added.')
return redirect('product')
except:
print(str(form.errors))
messages.error(request, str(form.errors))
else:
form = ProductForm()
context={
# 'noti':noti,
'form':form,
'title':'iPanel | Product Master',
'page_title':'Product List',
'tree_title_1':'Product',
'tree_title_2':'Add',
'tree_url':'product',
'btn_type':'fa fa-regular fa-plus',
}
return render(request,'panel/product/form.html',context)
It seems like the issue is with the validation of the form fields in the Django view. The error message suggests that some fields are required but are not being passed in the POST request.
In your jQuery code, you are serializing the form data and sending it as the data parameter in the AJAX call. However, since you are using enctype="multipart/form-data"
in your HTML form, you cannot simply use serialize()
method to serialize
the form data. Instead, you can use the FormData()
constructor to create a new FormData object and append the form fields to it.
Here’s how you can modify your jQuery
code:
var frm = $('#product_form');
frm.submit(function(e){
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
type:frm.attr('method'),
headers: { "X-CSRFToken": '{{ csrf_token }}' },
url:frm.attr('action'),
data:form_data,
contentType: false,
processData: false,
success:function(data){
$('#msg').html(data)
},
error:function(data){
$('#msg').html(data.responseText)
}
});
});
Read this article for more information