i got a page how have multiple POST method , so i used the action attribute in ajax to recognize each of the post method , but when i tried to use it on the form how add a model into the database (client model), it said 403 error invalid or missing csrf token, but when i remove the action and let only the REQUEST.METHOD == 'POST', it work , so i didnt understand why the csrf token is not working when i use the action , i solved the problem by getting directly the values of input form but is better if i use the automated feature of django forms so their is my old code .
ajax request:
$(document).ready(function(){
var csrfToken = $("input[name=csrfmiddlewaretoken]").val();
//$("#alert-container").hide();
//console.log(csrfToken);
$("#btn-submit").click(function() {
var serializedData = $("#ClientForm").serialize();
console.log("hey hey clients!");
$.ajax({
url: $("ClientForm").data('url'),
data :{serializedData,action: 'client'},
type: 'post',
success: function(response) {
console.log(response.client.name);
console.log($("#ClientList"))
}
})
$("#ClientForm")[0].reset()
});
});
html form :
<form class="contact-form" id="ClientForm" data-url="{% url 'addclient' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="name" class="sr-only">Name</label>
{{ form.name }}
</div>
<div class="form-group">
<label for="email" class="sr-only">Email</label>
{{ form.email }}
</div>
<div class="form-group">
<button type="button" id="btn-submit" class="btn btn-success btn-md">Add Client </client>
</div>
</form>
View.py:
def addclient(request):
form = ClientForm()
clients = client.objects.filter(affiliation=request.user.id)
Csession = session.objects.filter(coach=request.user.id)
context = {'form': form ,'clients': clients , 'Csession' : Csession}
#form = ClientForm
if request.method == 'POST' and request.POST['action'] == 'client':
form = ClientForm(request.POST)
print(form)
name = request.POST.get('name')
email = request.POST.get('email')
new_client = client.objects.create(name = name, email = email, affiliation = request.user)
new_client.save()
return JsonResponse({'client': model_to_dict(new_client)}, status=200)
#commment for the old code
'''if form.is_valid():
print('adding client 1133 to the hell', form)
name = request.POST.get('name')
email = request.POST.get('email')
new_client = client.objects.create(name= name, email=email , affiliation=request.user)
new_client.save()
return JsonResponse({'client': model_to_dict(new_client)}, status=200)
else:
print('not adding client to the form 1333 dahell')
return redirect('addclient')'''
#return JsonResponse({'session': model_to_dict(Sclient)}, status=200)
else:
print('not adding task')
#return redirect('addclient')
the working Ajax Code :
$(document).ready(function(){
var csrfToken = $("input[name=csrfmiddlewaretoken]").val();
$("#alert-container").hide();
//console.log(csrfToken);
$("#btn-submit").click(function() {
var serializedData = $("#ClientForm").serialize();
var data1 = $("input[name=name]").val();
var data2 = $("input[name=email]").val();
console.log("hey hey clients!");
$.ajax({
url: $("ClientForm").data('url'),
data : {
csrfmiddlewaretoken: csrfToken,
//serializedData,
name : data1,
email : data2,
action: 'client'
},
type: 'post',
success: function(response) {
console.log(response.client.name);
console.log($("#ClientList"))
//var block ='<div class="heading-section animate-box"> <h2>Client </h2> </div> </div> <div class="col-md-12"> <div class="fh5co-blog animate-box"> <div class="inner-post"> <a href="#"><img class="img-responsive" src="images/user.jpg" alt=""><i class="fa fa-user fa-5x" style="margin: 20px;"></i></a> </div> <div class="desc" style="padding-bottom: 2rem;"> <span class="posted_by"></span> <span class="comment"></a></span> <h3>'+ response.client.name +'</h3> <h3>'+ response.client.email +'</h3> <a href="addexercise.html" class="btn btn-success" style="margin-bottom: 1rem; margin-right: 2rem;">Add / Edit Exercises</a></div> <a href="client.html" class="btn btn-warning" style="margin-bottom: 1rem;">View</a> </div> '
//var test = '<h2>'+ response.client.name +'</h2>'
var test2 = document.createElement('div');
test2.innerHTML = '<div class="list-group list-group-me"> <ul class="list-group list-group-horizontal"> <li class="list-group-item">'+ response.client.name +'</li> <li class="list-group-item">'+ response.client.email +'</li> <li class="list-group-item"> Today </li> <li class="list-group-item list-group-item-warning">Inactive</li> <li class="list-group-item">025f55azg5</li> <button type="button" class="btn btn-outline-info">Client Not Active</button> </ul> </div>'
//var card = '<div class="card mt-2" id="taskCard" data-id="'+response.client.id+'"><div class="card-body" >'+ response.client.name +'<button type="button" class="close float-right" data-id="'+response.client.id+'" > <span aria-hidden="true">×</span></button></div></div>'
//$(block).appendTo("#clientList")
//$("#clientList").append(card).html();
document.getElementById("clientList").appendChild(test2)
//'<div class="col-md-12" id="clientList"><div class="col-md-12"><div class="heading-section animate-box"><h2>Client</h2></div></div> <div class="col-md-12"><div class="fh5co-blog animate-box"><div class="inner-post"><a href="#"><img class="img-responsive" src="images/user.jpg" alt=""><i class="fa fa-user fa-5x" style="margin: 20px;"></i></a></div><div class="desc" style="padding-bottom: 4rem;"><span class="posted_by"></span><span class="comment"></a></span><h3>Yoww</h3><a href="addexercise.html" class="btn btn-success" style="margin-bottom: 1rem; margin-right: 2rem;">Add / Edit Exercises</a><a href="client.html" class="btn btn-warning" style="margin-bottom: 1rem;">View</a></div> </div> </div>'
}
})
$("#ClientForm")[0].reset()
});
so i hope you can help me , i didnt understand why im facing this problem when using the action attribute.
Guesstimating a solution. You can try the below for ajax call and see if it works.
$(document).ready(function(){
var csrfToken = $("input[name=csrfmiddlewaretoken]").val();
//$("#alert-container").hide();
//console.log(csrfToken);
$("#btn-submit").click(function() {
var serializedData = $("#ClientForm").serializeArray();
serializedData.push({name:'action',value:'client'})
serializedData.push({name: 'csrfmiddlewaretoken', value: csrfToken})
console.log("hey hey clients!");
$.ajax({
url: $("ClientForm").data('url'),
data : serializedData,
type: 'post',
success: function(response) {
console.log(response.client.name);
console.log($("#ClientList"))
}
})
$("#ClientForm")[0].reset()
});