this is the views.py function for the backend
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from .models import Product, Wishlist
@csrf_exempt
@login_required
def add_to_wishlist(request):
product_id = request.GET.get('id')
product = Product.objects.get(id=product_id)
wishlist_count = Wishlist.objects.filter(product=product, user=request.user).count()
if wishlist_count > 0:
msg = "Product already exists in wishlist"
else:
Wishlist.objects.create(product=product, user=request.user)
msg = "Product added to wishlist"
wishlist_count = Wishlist.objects.filter(user=request.user).count()
request.session['wishlist_count'] = wishlist_count
return JsonResponse({"bool": wishlist_count > 0, 'totalwishlistitems': wishlist_count, 'msg': msg})
this is my functions.js ajax call to sent to the backend
$(document).ready(function () {
$(document).on('click', '.add-to-wishlist', function (event) {
event.preventDefault();
event.stopPropagation();
console.log('Button clicked');
let product_id = $(this).data("product-item");
console.log("Product ID is", product_id);
let this_val = $(this);
$.ajax({
url: "/add-to-wishlist",
data: { "id": product_id },
dataType: "json",
beforeSend: function () {
console.log('Before sending AJAX');
this_val.css("color", "red");
},
success: function (response) {
console.log('AJAX success', response);
this_val.toggleClass("wishlist-added", response.bool);
$(".wishlist-items-count").text(response.totalwishlistitems);
if (response.msg) {
console.log('Message from server:', response.msg);
// Create the message element
const message = $('<div class="wishlist-message">' + response.msg + '</div>');
console.log('Message element created:', message);
// Append the message element to the page
$('body').append(message);
console.log('Message element appended to body');
// Show the message element
message.fadeIn();
console.log('Message element faded in');
// Hide the message element after 3 seconds
setTimeout(function () {
message.fadeOut(function () {
$(this).remove();
console.log('Message element removed');
});
}, 3000);
} else {
console.log('No message received from server');
}
},
error: function (xhr, status, error) {
console.log('Error in AJAX request', error);
}
});
});
});
this is my index.html heat button to add to the wishlist url
{% for p in products %}
<div class="col-lg-3 col-md-4 col-sm-6 mix oranges fresh-meat">
<div class="featured__item">
<div class="featured__item__pic"
style="cursor: pointer; background-image: url('{{ p.image.url }}');"
onclick="redirectToProductDetail('{{ p.id }}')">
{% if p.get_percentage %}
<div class="discount-badge">
{{ p.get_percentage | floatformat:0 }}%
</div>
{% endif %}
<ul class="featured__item__pic__hover">
<li>
<div class="no-redirect-1">
<a class="add-to-wishlist" data-product-item="{{ p.id }} "><i class="fa fa-heart"></i></a>
</div>
</li>
<li>
<a class="no-redirect" onclick="shareProduct()"><i class="fa fa-share"></i></a>
<div id="shareModal" class="modal">
<div class="modal-content">
<h2>Share this product</h2>
<div class="share-icons">
<a href="https://www.messenger.com/" target="_blank" class="share-icon">
<i class="fab fa-facebook-messenger"></i> Messenger
</a>
<a href="https://www.instagram.com/" target="_blank" class="share-icon">
<i class="fab fa-instagram"></i> Instagram
</a>
<!-- Add more share options as needed -->
</div>
</div>
</div>
</li>
<li>
<div class="add-cart">
<input type="hidden" class="product-quantity-{{ p.id }}" value="1" id="product-quantity">
<input type="hidden" class="product-pid-{{ p.id }}" value="{{ p.pid }}">
<input type="hidden" class="product-image-{{ p.id }}" value="{{ p.image.url }}">
<input type="hidden" class="product-id-{{ p.id }}" value="{{ p.id }}">
<input type="hidden" class="product-title-{{ p.id }}" value="{{ p.title }}">
<a class="no-redirect add-to-cart-btn" data-index="{{ p.id }}">
<i class="fa fa-shopping-cart"></i>
</a>
</div>
</li>
</ul>
</div>
<div class="featured__item__text">
<span class="text-muted">{{ p.category }}</span>
<h6><a href="{% url 'core:product_detail' p.pid %}">{{ p.title }}</a></h6>
<div class="d-flex">
<h6>⭐⭐⭐⭐⭐</h6>
<h6>(5.0)</h6>
</div>
<h6 class="">By <a href="{% url 'core:vendor_detail' p.vendor.vid %}"><span
class="text-success">{{ p.vendor.title }}</span></a></h6>
<div class="d-flex justify-content-between align-items-center mt-2">
<div class="d-flex">
<h5 class="new-price current-product-price-{{p.id}}" value="{{ p.price }}"
id="current-product-price">{{ p.price }}</h5>
{% if p.old_price > 0 %}
<h5 class="old-price mx-3 text-muted" style="text-align: left;"><del>${{ p.old_price }}</del></h5>
{% else %}
<div></div>
{% endif %}
</div>
<div class="actions">
<input type="hidden" value="1" min="1" style="width: 50px;" id="product-quantity"
class="product-quantity-{{p.id}}">
<input type="hidden" value="{{ p.pid }}" class="product-pid-{{p.id}}">
<input type="hidden" value="{{ p.image.url}}" class="product-image-{{p.id}}" style="width: 50px;">
<input type="hidden" value="{{ p.id }}" class="product-id-{{p.id}}" style="width: 50px;">
<input type="hidden" value="{{ p.title }}" class="product-title-{{p.id}}">
<button class="btn btn-success add-to-cart-btn" id="add-to-cart-btn" data-index="{{ p.id }}">
<i class="fa fa-shopping-cart"></i> Add
</button>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
When using messages.success("Product has been added to wishlist")
in Django, the success message is added to the session and displayed on the next page load. This approach requires a page refresh for the message to appear, which is why you’re only seeing it after reloading the page.
New contributor
Sandesh Ranabhat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.