i am facing an issue sending a csv file and a bunch of data through ajax. I keep getting a Forbidden (CSRF token missing or incorrect) error even though I am sending the csrftoken. One more thing, I noticed that I am getting a different token in the code and cookies. I have also checked the Django CSRF documentation but it didn't help. Can anyone please assist me with this?
Here is the JavaScript code:
$('#upload').click(function(){
console.log('hello');
var store = $('#id_store').val();
var kitchen = $('#id_kitchen').val();
var form = $('.csv').prop('files')[0];
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
console.log(store)
data={
'csrfmiddlewaretoken':csrftoken,
'kitchen':kitchen,
'store':store,
'csv_file':form,
}
console.log(data)
$.ajax({
url: "{{url('custom-admin:csv_upload')}}",
type: 'POST',
data: data,
processData: false,
contentType:false,
success: function (data) {
if(data.status){
alert(data.message)
}
else{alert(data.message)}
}
});
})
HTML File:
<form id="demo-form2" method="post" data-parsley-validate="" class="form-horizontal form-label-left" enctype="multipart/form-data">
<div class="form-group">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
<label class="control-label col-md-3 col-sm-3 col-xs-5"> Store <span
class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12 stores" id="stores">
{{ form.store }}
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-5"> Kitchen <span
class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12 kitchen_list" id="kitchen_list">
{{ form.kitchen }}
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-5" > Upload File <span
class="required"></span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12 file">
{{form.csv_file}}
{% if form_errors.csv_file %}
<div class="alert alert-danger">{{form_errors.csv_file}}</div>
{% endif %}
</div>
</div>
<div class="form-group" >
<div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;">
<button type="button" class="btn btn-primary upload" id="upload"> Upload </button>
</div>
</div>
</form>
forms.py:
class CsvImportForm(forms.Form):
kitchen = forms.ChoiceField(
widget=forms.Select(attrs={
'type': "radio",
'class': "btn btn-primary btn-md",
'data-parsley-multiple': 'gender'
})
)
store = forms.ChoiceField(
widget=forms.Select(attrs={
'type': "radio",
'class': "btn btn-primary btn-md stores",
'data-parsley-multiple': 'gender'
})
)
csv_file = forms.FileField(
required=False,
widget=forms.FileInput(attrs={
'type': "file",
'class':"csv",
"data-validation": "mime",
'data-validation-allowing': "csv",
'data-validation-error-msg-mime': "You can only upload images in (csv)."
})
)