In the code below, I am using onclick (I know it may not be the best practice but for my particular situation I think it works best) to activate an ajax call to dynamically update the content on my Django template. As of now, the data is going to the back-end, and the Comment object is being created.
However, when returning a JSONResponse, the template is not using the data from this JSONResponse to update the page in any way. I have tried testing with alerts but to no avail. I am new to JS so I would love a little help! Thank you very much.
Django View:
def sochome(request, oid):
society = Society.objects.filter(id=oid).first()
membership = SocietyMembership.objects.get(member=request.user, society=society)
response_data = {}
if request.method == 'POST':
postID = request.POST.get('post_id')
comment_content = request.POST.get('comment')
response_data['post_id'] = postID
response_data['comment'] = comment_content
post = SocPost.objects.filter(id=postID).first()
SocComment.objects.create(post=post, author=request.user, content=comment_content)
# print(response_data, file=sys.stderr)
# print("SUCCESS JSON RESPONSE TO CLIENT SIDE", file=sys.stderr)
return JsonResponse(response_data)
context = {
'membership': membership,
'posts': society.posts.all().order_by('-date_posted')
}
return render(request, 'blog/sochome.html', context)
HTML:
< script type = "text/javascript" >
function update_comment(post_id) {
$.ajax({
type: 'POST',
url: "{% url 'blog-sochome' oid=membership.society.id%}",
data: {
'post_id': post_id,
'comment': document.getElementById(post_id.toString()).value
},
dataType: 'text',
success: function(data) {
alert("ajax completed ");
}
});
} <
/script>
<div id="{{post.id}}-comment-section" class="mb-3 pr-5 pt-4 pb-2 bg-light shadow-sm border-light" style="border-bottom-left-radius: 0.5rem; border-bottom-right-radius: 0.5rem;">
<div class="col-sm-12 pl-5 pb-5">
<form class="form-inline" method="POST" action="" style="display:flex" id="comment"> {% csrf_token %}
<input id="{{post.id}}" type="search" name="comment" placeholder="New comment" class="form-control mr-sm-2 p-4" style="flex-grow:1;">
<button name="post_id" class="btn btn-info my-2 my-sm-0 " value="{{post.id}}" onclick="update_comment({{post.id}})"> Post </button>
</form>
</div>
{% for comment in post.comments.all %}
<div class="row">
<div class="col-xs-1 offset-1 pl-4">
<img class="rounded-circle comment-image" src="{{ comment.author.profile.image.url }}" />
</div>
<div class="col-xs-4">
<a class="mr-2 comment-author-name" href="#">{{ comment.author.first_name }} {{ comment.author.last_name }}</a>
<small class="text-muted comment-time"><br>{{ comment.date_posted|date:"F d, Y" }}</small>
</div>
</div>
<div class="row">
<div class="col-sm-12 offset-1">
<p class="comment-content">{{ comment.content }}</p>
</div>
</div>
{% empty %}
<div class="px-5">
<p>No comments for this post.</p>
</div>
{% endfor %}
</div>
{% endfor %}
Related
I would like to make easy math in my currency Django project but I got response in google chrome inspect that one object (that which comes from API JSON response) is undefined but second is a String
When I change code a little bit to this below I got response in console inspect
And I can see clearly this object is there but I can't get it out of class .value
console.log(amount1, amount2);
<p id="crypto-price">3289.00221916 </p> <option id="user-wallet">15000 </option>
static/js/javascript.js
const amount1 = document.getElementById("crypto-price");
const amount2 = document.getElementById("user-wallet");
function calculate() {
console.log("YESS");
**console.log(parseInt(amount1.value) * parseInt(amount2.value));**
console.log(typeof amount1.value, typeof amount2.value);
}
calculate();
YESS
javascripts.js:13 NaN
javascripts.js:14 undefined string
Django templates where are both objects "crypto-price" "user-wallet" comes from the for loop
{% extends "web/layout.html" %}
{% block body %}
<div class="row">
{% for crypto_detail in crypto_detail_view %}
<div class="col-lg-12 col-md-6 mb-4">
<div class="card h-100">
<div class="card-body">
<img class="rounded mx-auto d-block" src="{{crypto_detail.logo_url}}" width="50" height="50">
<h4 class="card-title text-center" id="crypto-name">{{ crypto_detail.name }} </h4>
</div>
<div class="card-footer text-center">
<p id="crypto-price" >{{crypto_detail.price}} </p>
<p>{{fiat_currency}}</p>
</div>
<div class="card-footer text-center" >
<p href="">Price Date: {{ crypto_detail.price_date }}</p>
</div>
</div>
</div>
{% endfor %}
<div class="row g-3 align-items-center">
<p>Your Money:</p>
<select class="form-select" aria-label="Default select example">
<option selected>which currency do you want to buy Crypto for?</option>
{% for money_purchased in user_purchased_currencies %}
<p id="currency-name">{{money_purchased.currency}}</p>
<option id="user-wallet">{{money_purchased.currency_amount}} </option>
{% endfor %}
</select>
<form method="post" >
{% csrf_token %}
<div class="form-group">
<p>{{ form.wallet_amount }}</p>
<input type="text" value="{{crypto_name}}" />
</div>
<input class="btn btn-primary" type="submit" value="Buy">
</form>
</div>
</div>
{% block js_block %}
<script src="/static/js/javascripts.js" ></script>
{% endblock %}
{% endblock %}
This is what my page looks like:
I have a sidebar which can change the contents of the page depending on the button clicked. When I click on About the page will look like this:
So I made this with Vanilla JS using inner.HTML.
PROBLEM: When I refresh the page, meaning the inner.HTML is not happening yet because I never clicked any buttons on the sidebar yet. My form submits properly and it does not redirect me to the API url used on the form. But, when I tried to click the About button and click Home button and try to submit the form again, it redirects me now to the API page used on the form. My guess is, there is something wrong with my vanillajs using inner.HTML.
CODE looks like this:
HTML:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block script %}
<script type="text/javascript" src="{% static 'js/cms/cms.js' %}"></script>
{% endblock %}
{% block style %}
<link rel="stylesheet" type="text/css" href="{% static 'css/cms.css' %}">
{% endblock %}
{% block content %}
<div class="container">
<div class="sticky-sidebar-page">
<div class="sidebar">
<h3>Manage Site Contents</h3>
<div class="list-group">
<button class="list-group-item list-group-item-action active" aria-current="true" onClick="showHomeContent()" id="homeButton">Home</button>
<button class="list-group-item list-group-item-action" aria-current="true" onClick="showAboutContent()" id="aboutButton">About</button>
Contact Us
Sample Page
A disabled link item
</div>
</div>
<div class="sandbox">
<div class="page-content" id="page-content">
<!-- SCHOOL LOGO -->
<div class="card" id="school-logo">
<div class="card-body">
<h5>School Logo</h5>
<small>On display:</small> <br>
<img src="{{logo.image.url}}" id="img" class="card-img-top" alt="..." style="max-width: 10rem; max-height: 10rem;"> <br>
<small>Change:</small>
<form action="{% url 'changelogo' %}" method="POST" enctype="multipart/form-data" id="logo-form">
{% csrf_token %}
<div class="input-group mb-3">
<input type="file" name="image" class="form-control" required id="inputGroupFile02">
<button type="submit" class="input-group-text" for="inputGroupFile02">Upload
</button>
</div>
</form>
</div>
</div>
<!-- HOME CAROUSEL -->
<div class="card">
<div class="card-body">
<h5>Home Carousel</h5>
<small>On display:</small><br>
{% for pic in carouselpics %}
<img src="{{pic.image.url}}" class="card-img-top" alt="..." style="max-width: 15rem; max-height: 15rem;"> <br>
Label: {{pic.label}} <br>
Content: {{pic.content}}<br>
<span style="font-size: 20px;">
<span style="color: red;">
<i class="fas fa-trash-alt"></i>
</span>
<span style="color:brown">
<i class="far fa-edit"></i>
</span>
</span>
<br>
<hr>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
const csrftoken = "{{csrf_token}}"
//home contents
var changeLogoUrlView = "{% url 'changelogo' %}"
var schoolLogo = "{{logo.image.url|safe}}";
</script>
JS:
const pageContent = document.getElementById('page-content')
// Getting Home Page Contents
function getLogo(){
var url = "http://localhost:8000/web-content/api/changelogo/"
fetch(url)
.then((response) => response.json())
.then(function(data){
pageContent.innerHTML = `
<div class="card" id="school-logo">
<div class="card-body">
<h5>School Logo</h5>
<small>On display:</small> <br>
<img src="${data[0].image}" id="img" class="card-img-top" alt="..." style="max-width: 10rem; max-height: 10rem;"> <br>
<small>Change:</small>
<form action="http://localhost:8000/web-content/api/changelogo/" method="POST" enctype="multipart/form-data" id="logo-form">
<input type="hidden" name="csrfmiddlewaretoken" value="${csrftoken}" >
<div class="input-group mb-3">
<input type="file" name="image" class="form-control" required id="inputGroupFile02">
<button type="submit" class="input-group-text" for="inputGroupFile02">Upload
</button>
</div>
</form>
</div>
</div>
`
})
}
function showHomeContent(){
if ( document.getElementById("homeButton").className.match(/(?:^|\s)active(?!\S)/) ){
return;
}else{
document.getElementById('homeButton').classList.add('active')
}
if ( document.getElementById("aboutButton").className.match(/(?:^|\s)active(?!\S)/) ){
document.getElementById("aboutButton").classList.remove('active')
}
pageContent.innerHTML = ""
getLogo()
}
function showAboutContent(){
if ( document.getElementById("aboutButton").className.match(/(?:^|\s)active(?!\S)/) ){
return;
}else{
document.getElementById('aboutButton').classList.add('active')
}
if ( document.getElementById("homeButton").className.match(/(?:^|\s)active(?!\S)/) ){
document.getElementById("homeButton").classList.remove('active')
}
pageContent.innerHTML = `
this is about content
`
}
// formsssssss
// change logo
var logoform = document.getElementById('logo-form')
logoform.addEventListener('submit', function(e){
e.preventDefault()
let input = document.getElementById('inputGroupFile02');
let data = new FormData();
data.append('image',input.files[0]);
var url = "http://localhost:8000/web-content/api/changelogo/"
fetch(url,{
method: "POST",
headers: {
"X-CSRFToken": csrftoken,
},
body:data
})
.then((response) => response.json())
.then(function(data){
getLogo()
logo = document.getElementById('logo-div')
logo.innerHTML = ""
logo.innerHTML = `<img src="${data.image}" alt="no image provided" style="max-width: 7rem; max-height: 7rem;">`
})
})
views.py:
this is the view I am using to for the change logo form where the problem happens when submitting after the page is rendered with inner.HTML:
class ChangeLogo(generics.ListCreateAPIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated, IsAdminUser]
serializer_class = SchoolLogoSerializer
queryset = SchoolLogo.objects.all()
I tried posting before but I was not able to get a clear answer so I thought I would reframe it simply.
My template currently uses a for loop to print the posts of a "blog" and another for loop inside that to print comments belonging to the post.
Before I continue, just want to make it clear that my models and database is functioning. I even currently have a working comment section, it just keeps refreshing the page and so I would like to incorporate JS and AJAX instead.
Because I have multiple posts with their own comment sections, I tried creating individual id's for each form in the loop by saying . However, I am slightly confused as to how I am supposed to create an EventListener to make sure that no matter which of these forms are pressed, it takes the correct data and sends it to the backend.
Any help would be appreciated. Thank you! Code upon request is available. However, I would like to stress that it is unnecessary to ask for my model code as it works just fine.
{% for post in posts %}
<div class="mt-3 px-5 pt-4 pb-2 bg-white shadow-sm" style="border-top-left-radius: 0.5rem; border-top-right-radius: 0.5rem;">
<div class="row">
<div class="col-xs-1 pl-4">
<img class="rounded-circle post-image" src="{{ post.author.profile.image.url }}" />
</div>
<div class="col-xs-4 pt-1">
<a class="mr-2 post-author-name" href="#">{{ post.author.first_name }} {{ post.author.last_name }}</a>
<small class="text-muted post-time"><br>{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<div class="col-xs-7 ml-3 pt-2">
Click for more options
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p class="post-content">{{ post.content }}</p>
</div>
</div>
</div>
<div class="mb-3 pr-5 pt-4 pb-2 bg-light shadow-sm border-light" style="border-bottom-left-radius: 0.5rem; border-bottom-right-radius: 0.5rem;">
<div class="col-sm-12 pl-5 pb-5">
<form class="form-inline" method="POST" style="display:flex" id="{{forloop.counter}}"> {% csrf_token %}
<input type="search" name="comment" placeholder="New comment" class="form-control mr-sm-2 p-4" style="flex-grow:1;">
<button name="post_id" class="btn btn-info my-2 my-sm-0 " value="{{post.id}}" onclick='update_comments("{{forloop.counter}}")'> Post </button>
</form>
</div>
{% for comment in post.comments.all %}
<div class="row">
<div class="col-xs-1 offset-1 pl-4">
<img class="rounded-circle comment-image" src="{{ comment.author.profile.image.url }}" />
</div>
<div class="col-xs-4">
<a class="mr-2 comment-author-name" href="#">{{ comment.author.first_name }} {{ comment.author.last_name }}</a>
<small class="text-muted comment-time"><br>{{ comment.date_posted|date:"F d, Y" }}</small>
</div>
</div>
<div class="row">
<div class="col-sm-12 offset-1">
<p class="comment-content">{{ comment.content }}</p>
</div>
</div>
{% empty %}
<div class="px-5">
<p>No comments for this post.</p>
</div>
{% endfor %}
</div>
{% endfor %}
I am building a website which users can create posts and comment on it, however, after clicking the submit button in the post_detail.html template to submit the comment, nothing happens and I cannot een see an error. I am using jQuery to submit the form
this is my post_detail view:
#login_required
def post_detail(request, id):
data = dict()
post = get_object_or_404(Post, id=id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(False)
comment.post = post
comment.name = request.user
comment.save()
comments = post.comments.all()
data['form_is_valid'] = True
data['comments'] = render_to_string('home/posts/post_detail.html', { 'comments':comments }, request=request)
else:
data['form_is_valid'] = False
else:
form = CommentForm
comments = post.comments.all()
context = {
'form': form,
'comments': comments,
'post': post
}
data['html_data'] = render_to_string('home/posts/post_detail.html', context,request=request)
return JsonResponse(data)
this is my post_detail.html template:
{% load crispy_forms_tags %}
{% load static %}
<script src="{% static 'js/comment.js' %}"></script>
<div class="modal-header-sm">
<button type="button" class="close mx-2" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card mt-3 rounded-0 mb-3" style="max-width: 100rem !important;">
<div class="card-body text-dark">
<div class="d-flex">
<img class="img-create-post rounded-circle mr-2" style="width: 50px;height: 50px;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg"
alt="Profile image">
<span class="align-text-top"><a class="mr-2 text-dark font-weight-bolder" href="#">{{ post.author.first_name }} {{ post.author.last_name }} </a><br><p class="font-weight-light text-muted">{{ post.title }}</p></span>
<div class="float-right text-right ml-auto">
<p class="text-muted small" style="font-size: 0.7rem;">{{ post.date_posted|date:"F d, Y" }}</p>
</div>
</div>
<p class="card-text">{{ post.content }}</p>
</div>
<div class="card-footer" style="height: 5rem;">
<a class="mx-1 small" data-href='{{ post.get_api_like_url }}' data-likes='{{ post.likes.count }}' href='{{ post.get_like_url }}'><i class="fas fa-thumbs-up"></i> Like</a>
<hr class="my-1">
<p class="text-muted small">
{% if post.author == request.user %}
<button class="btn btn-sm text-muted show-form-delete ml-auto" data-url="{% url 'home:post-delete' post.id %}" style="font-size: small;" style="height: 0rem;">Remove</button>
{% endif %}
<small class="float-sm-right">
{{ post.likes.count }} Likes, {{ post.comments.count }} Comments
</small>
</p>
</div>
<div class="card-body">
<div class="row">
<img class="img-create-post rounded-circle mr-2" style="width: 40px;height: 40px;" src="{{ request.user.image }}" alt="Profile image">
<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
{% csrf_token %}
<div class="row ml-1">
{{ form | crispy }}
<button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button>
</div>
</form>
</div>
<hr>
</div>
<div id="post-linked-comments">
<div>
{% include 'home/posts/post_comment.html' %}
</div>
</div>
</div>
the post_comment.html template for your reference however it is most likely not the issue:
<ul class="list-group list-group-flush">
{% for comment in comments %}
<li class="list-group-item">
<div class="d-flex">
<img class="img-create-post rounded-circle mr-1" style="width: 20px;height: 20px;" src="{{ comment.name.image }}"
alt="Profile image">
<span class="align-text-top font-weight-bolder">{{ comment.name.first_name }}
<p class="text-muted small mx-2" style="font-size: 0.7rem;">{{ comment.created_on|date:"F d, Y at: f A" }}</p><br>
<p class="font-weight-light">{{ comment.body }}</p></span>
</div>
</li>
{% empty %}
<li class="list-group-item">
<div class="d-flex">
<p class="font-weight-lighter text-muted">No comments to show</p>
</div>
</li>
{% endfor %}
</ul>
and finally my javascript code in comment.js:
$(document).ready(function(){
var ShowForm = function(e){
e.stopImmediatePropagation();
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType:'json',
beforeSend: function(){
$('#modal-post-detail').modal('show');
},
success: function(data){
$('#modal-post-detail .modal-content').html(data.html_data);
}
});
};
var SaveForm = function(e){
e.stopImmediatePropagation();
var form = $(this);
$.ajax({
url: form.attr('data-url'),
data: form.serialize(),
type: form.attr('method'),
dataType: 'json',
success: function(data){
if(data.form_is_valid){
$('#post-linked-comments div').html(data.comments);
alert('Comment added')
} else {
$('#modal-post-detail .modal-content').html(data.html_data)
}
}
})
return false;
}
//adding a comment
$('.comment-post-btn').click(ShowForm);
$('.post-detail-clickable-details-view').click(ShowForm);
$('#modal-post-detail').on("submit",".post-comment-form",SaveForm)
});
There is no issue with getting the Javascript file as the post_detail modal pops up fine, however after clicking on the add button nothing happens.
Thanks for all the help in advance.
EDIT: Button should be added inside the form but now NoReverseMatchException is being thrown after clicking on 'Add' button:
New Form:
<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
{% csrf_token %}
<div class="row ml-1">
{{ form | crispy }}
<button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button>
</div>
</form>
urls.py:
path('post/<int:id>/', views.post_detail, name='post-detail'),
Error:
django.urls.exceptions.NoReverseMatch: Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['home/post/(?P<id>[0-9]+)/$']
SOLVED: I managed to solve the issue myself. it was from my views. I was sending the comments to the wrong html template. Below you can see the corrected view for the template.
#login_required
def post_detail(request, id):
data = dict()
post = get_object_or_404(Post, id=id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(False)
comment.post = post
comment.name = request.user
comment.save()
comments = post.comments.all()
data['form_is_valid'] = True
#data['comments'] = render_to_string('home/posts/post_detail.html', { 'comments':comments }, request=request)
#corrected code below
data['comments'] = render_to_string('home/posts/post_comment.html', { 'comments':comments }, request=request) else:
data['form_is_valid'] = False
else:
form = CommentForm
comments = post.comments.all()
context = {
'form': form,
'comments': comments,
'post': post
}
data['html_data'] = render_to_string('home/posts/post_detail.html', context,request=request)
return JsonResponse(data)
I believe nothing is happening since the submit button is not defined within any form tags.
From the code in post_detail.html the button tags are outside the form tags.
<div class="row">
<img class="img-create-post rounded-circle mr-2" style="width: 40px;height: 40px;" src="{{ request.user.image }}" alt="Profile image">
<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
{% csrf_token %}
<div class="moda-body">
{{ form | crispy }}
</div>
</form>
<button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button>
</div>
The button tag should be placed before the closing tag of the form.
<div class="row">
<img class="img-create-post rounded-circle mr-2" style="width: 40px;height: 40px;" src="{{ request.user.image }}" alt="Profile image">
<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
{% csrf_token %}
<div class="moda-body">
{{ form | crispy }}
</div>
<button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button>
</form>
</div>
when i press button, this error is blow up
Forbidden (CSRF token missing or incorrect.): /orders/basket_adding/
/
I take csrf_token from the form on the main page, all the others
inherit from the page where the form is, from where I get the token!
Pls help me)
views
def basket_adding(request):
print('HER')
return_dict = {}
session_key = request.session.session_key
data = request.POST
context = {}
return JsonResponse(return_dict)
/////
/////
html
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<div class="single">
<div class="container">
<div class="single-main">
<div class="single-top-main">
<div class="col-md-5 single-top">
<div class="flexslider">
<ul class="slides">
{% for img in images %}
<li data-thumb="{{ img.image.url }}">
<div class="thumb-image"> <img src="{{ img.image.url }}" data-imagezoom="true" class="img-responsive"> </div>
</li>
{% endfor %}
</ul>
</div>
</div>
<div class="col-md-7 single-top-left simpleCart_shelfItem">
<h2>{{ product_himself.brand.name_of_brand }}</h2>
<h1 class="product_name" action="{% url 'orders:basket_adding' %}" >{{ product_himself.name_of_product }}</h1>
<p class="hidden product_id">{{ product_himself.id }}</p>
{% if product_himself.discount %}
<span>$<strike>{{ product_himself.price_of_product }}</strike> $<span class="item_price">{{ product_himself.price_with_discount }}</span></span>
{% else %}
$<h6 class="item_price">{{ product_himself.price_of_product }}</h6>
{% endif %}
<p>{{ product_himself.description }}</p>
<h4>Size</h4>
<ul class="bann-btns">
<li><select class="bann-size">
<option value="s">Small</option>
<option value="m">Medium</option>
<option value="l">Large</option>
</select>
</li>
<li>Add To Cart</li>
</ul>
</div>
<div class="clearfix"> </div>
</div>
<div class="singlepage-product">
{% for smart in img_bran %}
<div class="col-md-3 home-grid">
<div class="home-product-main">
<div class="home-product-top">
<img src="{{ smart.image.url }}" alt="" class="img-responsive zoom-img">
</div>
<div class="home-product-bottom">
<h3>{{ smart.access_to_product.description|truncatechars:25 }}</h3>
<p>Explore Now</p>
</div>
<div class="srch">
<span>${{ smart.access_to_product.price_of_product }}</span>
</div>
</div>
</div>
{% endfor %}
<div class="clearfix"> </div>
</div>
</div>
</div>
</div>
{% endblock content %}
base html (where located form, from which i take csrf_token)
<div class="hidden">
<form class="default_form"></form>{% csrf_token %}
</div>
////
js
$(document).ready(function(){
$(document).on('click', '.item_add', function(e){
e.preventDefault();
product_id = $(".product_id").html();
product_name = $(".product_name").html();
product_price = parseFloat($(".item_price").html())
product_size = $(".bann-size").val();
url = $(".product_name").attr("action");
console.log(url)
var data = {};
var csrf_token = $('.default_form [name="csrfmiddlewaretoken"]').val();
data.product_id = product_id
data.product_name = product_name
data.product_price = product_price
data.product_size = product_size
data["csrfmiddlewaretoken"] = csrf_token;
$.ajax({
url: url,
type: 'POST',
data: data,
cache: true,
success: function(data){
console.log("OK");
},
error: function(data){
console.log(data + "ERROR")
alert("Something wrong, try again!")
location.reload();
}
});
});
});
Your problem is you have not inserted CSRF token in form tag so it will not get any CSRF token.
for example
<div class="hidden">
<form class="default_form">
{% csrf_token %}
</form>
</div>