[Answered ]-Using jquery POST request to save form in django

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)

Leave a comment