1π
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
0π
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)
- [Answered ]-Goose-extractor for python 3.4 Error
- [Answered ]-How to create Django model field to store users related to the model?
- [Answered ]-TastyPie authentication for pure javascript site
- [Answered ]-Integrate Visa and Mastercard in DJango 1.8 app
- [Answered ]-Using FormWizard and saving the forms data in between before the completion of the whole process?