MultipleObjectsReturned at /course/eyime/user_library/ - python

I am building a website where users can buy courses and the courses will display on their users library, a site similar to gumroad, but i am getting this error when i clicked on the payment option on my code.
Here is the error messages i am getting
MultipleObjectsReturned at /course/eyime/user_library/
get() returned more than one UserLibrary -- it returned 2!
here is the Views.py codes
#login_required
def user_library(request, username):
user = get_object_or_404(User, username=username)
my_library = UserLibrary.objects.filter(user=user)
if request.method == 'POST':
course_id = request.POST['course_id']
course_price = request.POST['course_price']
course = UserLibrary.objects.get(courses__id=course_id)
"""for c in course.courses.all():
print(c.name)"""
context = {
'course': course,
'course_price': course_price,
'email': request.user.email,
'phone': request.user.phone_number,
}
return render(request, 'courses/content/pay_for_courses.html', context)
return render(request, 'courses/content/user_library.html', {'my_library': my_library})
here is the html codes for payment of the courses
{% extends "jtalks/base.html" %}
{% load static %}
{% block title %}Payment With Paystack{% endblock %}
{% block content %}
<div class='container' onload="payWithPaystack()">
<div class='row justify-content-md-center'>
<div class='col-md-auto'>
<div id="output">
</div>
<div id="success">
</div>
<div id="display_info" style="display: none">
<p>Click Here to print receipt of your purchase</p>
<p id="home">Go Back Home Homepage</p>
</div>
</div>
</div>
</div>
{% endblock content %}
{% block js %}
<script src="https://js.paystack.co/v1/inline.js"></script>
<script>
window.onload=function(){
payWithPaystack();
};
function payWithPaystack(){
var price = '{{ course_price }}';
var handler = PaystackPop.setup({
key: 'pk_test_ce8979497f703eb955ab5ceb19fc54cdcb615e0d',
email:'{{email}}',
amount: parseInt(price) * 100,
currency: "NGN",
metadata: {
custom_fields: [
{
display_name: "Mobile Number",
variable_name: "mobile_number",
value: "{{phone}}",
course_id: "{{ course.id }}"
}
]
},
callback: function(response){
var ref = response.reference;
var course_random_id = '{{ course.order_id }}'
var course_id = '{{ course.id }}'
//console.log(order_id)
// $('div#home').show();
$.ajax({
method: "GET",
url: "/course/pay_for_courses/",
data: {
'id': course_id,
'reference': ref,
},
dataType: "json",
success: function (data) {
if (data.message == "Your Payment was successfully received") {
$('#output').html(data.message)
$('#success').html(`<p>Transaction reference is : <h2>${ref}</h2> and your order id is <h2>${course_random_id}</h2></p>`);
$("#display_info").show();
} else if (data.message == "Your Payment Failed!!!") {
$('#output').html(data.message)
$("#success").html(`Back To Your Library`)
}
},
});
},
onClose: function(){
alert('window closed');
}
});
handler.openIframe();
}
</script>
{% endblock js %}
and here is the html codes for users library
{% extends 'jtalks/base.html' %}
{%load static%}
{% block content %}
<div>
<center>Welcome to your library, {{ request.user.username }}</center>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-6">
<h1>Wish List</h1>
<h3>Courses you are yet to pay for will show up here</h3>
<div class="user_library" style="display: flex; flex-direction: row; flex-wrap: wrap;">
{% for library in my_library %}
{% if not library.paid %}
{% for course in library.courses.all %}
<div class="card" style="width: 18rem;">
<img src="{{ course.content_file.url }}" class="card-img-top" alt="{{ course.name }}">
<div class="card-body">
<h5 class="card-title">{{ course.name }}</h5>
<p class="card-text">{{ course.overview|slice:":50" }}...</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">An item</li>
<li class="list-group-item">A second item</li>
<li class="list-group-item">A third item</li>
</ul>
<div class="card-body">
Course Details
<form method="post">
{% csrf_token %}
<input type="hidden" name="course_id" value="{{ course.id }}">
<input type="hidden" name="course_price" value="{{ course.price }}">
<input type="submit" class="btn btn-primary" value="Pay ₦{{ course.price}}">
</form>
</div>
</div>
{% endfor %}
{% endif %}
{% endfor %}
</div>
</div>
<div class="col-6">
<h1>Paid Courses</h1>
<h3>All courses you have successfully paid for will show here</h3>
<div class="user_library" style="display: flex; flex-direction: row; flex-wrap: wrap;">
{% for library in my_library %}
{% if library.paid %}
{% for course in library.courses.all %}
<div class="card" style="width: 18rem;">
<img src="{{ course.content_file.url }}" class="card-img-top" alt="{{ course.name }}">
<div class="card-body">
<h5 class="card-title">{{ course.name }}</h5>
<p class="card-text">{{ course.overview|slice:":50" }}...</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">An item</li>
<li class="list-group-item">A second item</li>
<li class="list-group-item">A third item</li>
</ul>
<div class="card-body">
Course Details
<a id="download_pdf" href="/media/pdf_courses/{{ course.slug }}.pdf" class="btn btn-primary" download>Download PDF</a>
</div>
<div>
<video width="300" height="240" controls controlsList="nodownload">
<source src="{{ MEDIA_URL}}{{ course.course_video }}" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
{% endfor %}
{% endif %}
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}
{% block js %}
<script src="{% static 'jtalks/home.js' %}"></script>
{% endblock js %}

It seems that this line is returning 2 records instead of one:
course = UserLibrary.objects.get(courses__id=course_id)
Use filter instead of get and iterate through the course variable in a template tag such as:
{% for c in course %}
and access c's fields instead.

Related

Django - Confirmation popup

I'm trying to write a code for deleting an item. But before deleting it i want to popup a message to the user like "are you sure you want to delete?".
I want to delete the item by its ID.
I wrote this code, but i pretty sure its not how it should be.
Please guide me what to do.
HTML FILE
<div id="film_box">
{% if films %}
{% for film in films %}
<div class="card" style="width: 18rem;">
{% if film.image%}
<img src="{{ film.image.url }}" class="card-img-top" alt="...">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ film.title}}</h5>
<p class="card-text">{{ film.category_name }}</p>
<p class="card-text">{{ film.country_name }}</p>
<p class="card-text">{{ film.director }}</p>
<p class="card-text">{{ film.release_date }}</p>
</div>
<div class="card-body">
{% if request.user.is_superuser %}
<ul style="list-style:none;">
<li>Modify the director
</li>
<li>Modify the film</li>
<li><button onclick="document.getElementById('btn_delete').style.display='block'"
name="{{ film.id }}" class="btn btn-danger">DELETE</button></li>
</ul>
{% endif %}
<!--popup message-->
<div id="btn_delete" class="modal">
<span onclick="document.getElementById('btn_delete').style.display='none'" class="close" title="Close
Modal">×</span>
<form class="modal-content" action="/delete/{{film.id}}">
<div class="container">
<h1>Delete film</h1>
<p>Are you sure you want to delete the film?</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('btn_delete').style.display='none'" class="cancelbtn">Cancel</button>
<button href="{% url 'delete_film' film.id %}" onclick="document.getElementById('btn_delete').style.display='none'" class="deletebtn">Delete</button>
</div>
</div>
</form>
</div>
{% endfor%}
{% endif %}
JAVASCRIPT FILE
// Get the modal
var modal = document.getElementById('btn_delete');
console.log(model.name)
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
I want to pass the ID in the url, so i can catch it on the python file and manipulate it.
Should i use Javascript?
This is how I would do it. Please note the code is not tested, however the principles should give you a glimpse of understanding of how to proper do it.
from django.http import JsonResponse
from django.views import generic
# urls.py
urlpatterns = [
re_path(r'^delete/(?P<pk>.+)/$', views.DeleteFilmView.as_view(), name='delete'),
]
# models.py
class Film(models.Model):
# ...
def get_delete_url(self):
return reverse('film:delete', args=(self.pk,))
# views.py
class DeleteFilmView(generic.DeleteView):
template_name = 'delete_confirmation.html'
model = Film
context_object_name = 'film'
def delete(self, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
self.object.delete()
return JsonResponse({'messages': 'Deleted'})
<!--html file-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete Film</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="film_box">
{% if films %}
{% for film in films %}
<div class="card" style="width: 18rem;">
{% if film.image%}
<img src="{{ film.image.url }}" class="card-img-top" alt="...">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ film.title}}</h5>
<p class="card-text">{{ film.category_name }}</p>
<p class="card-text">{{ film.country_name }}</p>
<p class="card-text">{{ film.director }}</p>
<p class="card-text">{{ film.release_date }}</p>
</div>
<div class="card-body">
{% if request.user.is_superuser %}
<ul style="list-style:none;">
<li>Modify the director
</li>
<li>Modify the film</li>
<li>Delete</li>
</ul>
{% endif %}
</div>
</div>
</div>
<script type="text/javascript">
(function () {
$('.deletePopup').on('click',function(){
$('.modal-body').load('content.html',function(){
$('#myModal').modal({show:true});
});
});
$('body').on('click', '.delete-film', function(e) {
// make sure you listen on the body and not on the element, because the element doesnt exist when
// DOM is created.
e.preventDefault():
$.ajax({
url: $(this).attr('href');,
type: 'DELETE',
dataType: 'json',
success: function(result) {
// show success message, ie: using toastr
// remove the film from DOM
// close the modal
}
})
})
})();
</script>
<!--delete_confirmation.html-->
<p>Are you sure you want to delete {{ film.title}}?</p>
<a class="delete-film" href="{{ film.get_delete_url }}">Delete</a>
Cancel

Django change object details when button is clicked

Good evening!
I want to make two buttons, when one is clicked automatically change details of this object. I've already set to view two models but i don't know how to manage change only one post. Whether I should use template tag or try to use JS (which frankly I don't know how to use) Thanks for your replies!
views.py
class PostList(ListView):
template_name = 'post/index.html'
ordering = ['-date']
queryset = EveryPostPl.objects.all()
def get_context_data(self, **kwargs):
context = super(PostList, self).get_context_data(**kwargs)
context['EveryPostRu'] = EveryPostRu.objects.all()
context['EveryPostPl'] = self.queryset
return context
html
{% extends "post/base.html" %}
{% block title %}
<title>Home Page</title>
{% endblock title %}
{% block content %}
{% for obj in EveryPostPl %}
<div class="card text-center">
<div class="card-header">
<ul class="nav nav-tabs card-header-tabs">
<li class="nav-item">
<a class="nav-link nav-main" href="#">PL</a>
</li>
<li class="nav-item">
<a class="nav-link nav-main" href="#">RU</a>
</li>
</ul>
</div>
<div class="card-body">
<h5 class="card-title">{{ obj.title }}</h5>
<p class="card-text">{{ obj.text|truncatechars:350 }}</p>
Zobacz
</div>
<div class="card-footer text-muted">
<span class="float-left">{{ obj.date|date:"d M y" }}</span>
<span class="float-right">Przesłane przez: {{ obj.User }}</span>
</div>
</div>
{% endfor %}
{% endblock content %}
enter image description here
This would work if you don't mind sending all the details to the client:
<html>
<head>
<title>JS Test</title>
<script>
function switch_to(elem_id) {
var content_divs = document.getElementsByClassName("content");
for(var i = 0; i < content_divs.length; i++){
content_divs[i].style.display = "none";
}
var elem = document.getElementById(elem_id);
elem.style.display = "block";
}
</script>
</head>
<body>
RU
PL
<div id="RU" class="content">
Some text about RU...
</div>
<div id="PL" class="content" style="display:none">
Some text about PL
</div>
</body>
</html>
(for whatever reason it won't run as a code snippet...)

What's problem with this pagination code?

This code already have done the pagination ,but it false because per page it shows all items in the database ,and the same in other pages
This is the routing
#app.route('/shop/page/<int:page_num>')
def shop(page_num):
products=Product.query.filter
(Product.category.has(Product.category_id))
shopPage=Product.query.paginate
(page=page_num,per_page=5,error_out=True)
return render_template('shop.html',
shopPage=shopPage,products=products)
And this is the HTML code of pagination and the output products of database
{% block content %}
<div class="mb-5">
{% for product in products %}
<div class="col-4 mt-3 ">
<div class="card">
<div class="card-header">
<form method="POST" action="{{ url_for('shop') }}" >
</form>
</div>
<div class="card-body">
<h5 class="card-title">{{product.name }}</h5>
<p class="card-text">
<div>Category: {{ product.category.name }}</div>
<div>Price: {{ product.price }} $</div>
<div>Company: {{ product.company }}</div>
</p>
</div>
</div>
</div>
{% endfor %}
</div>
{% for page in shopPage.iter_pages(left_edge=2, right_edge=2, left_current=1, right_current=2) %}
{% if page %}
<nav >
<ul class="pagination ">
<li class="page-item ">
<a class="page-link" href="{{url_for('shop',page_num=page)}}" tabindex="-1">{{ page }}</a>
</li>
</ul>
</nav>
{% else %}
...
{% endif %}
{% endfor %}
{% endblock %}

How to send file from Mayan EDMS to external api?

I'm still learning Django and there is still a lot of unknown to me.
The problem is that I can't pull the .pdf (or any other format) to be sent by ajax post method to external API. So on the reciving side I only get the string location of the file not the actual file.
I have put the following javascript code in the generic_list_items_subtemplate.html
{% load i18n %}
{% load static %}
{% load common_tags %}
{% load navigation_tags %}
<div class="row">
<div class="col-xs-12">
<h4>
{% if page_obj %}
{% if page_obj.paginator.num_pages != 1 %}
{% blocktrans with page_obj.start_index as start and page_obj.end_index as end and page_obj.paginator.object_list|length as total and page_obj.number as page_number and page_obj.paginator.num_pages as total_pages %}Total ({{ start }} - {{ end }} out of {{ total }}) (Page {{ page_number }} of {{ total_pages }}){% endblocktrans %}
{% else %}
{% blocktrans with page_obj.paginator.object_list|length as total %}Total: {{ total }}{% endblocktrans %}
{% endif %}
{% else %}
{% blocktrans with object_list|length as total %}Total: {{ total }}{% endblocktrans %}
{% endif %}
</h4>
<hr>
<div class="well center-block">
<div class="clearfix">
<div class="pull-right">
<form action="{% url 'common:multi_object_action_view' %}" class="form-multi-object-action" method="get">
{% if object_list %}
{% if not hide_multi_item_actions %}
{% get_multi_item_links_form object_list %}
{% endif %}
{% if multi_item_actions %}
<fieldset style="margin-top: -10px;">
<input class="check-all" type="checkbox"/>
{{ multi_item_form }}
</fieldset>
{% endif %}
{% endif %}
</form>
</div>
</div>
{% if object_list %}
<hr style="border-bottom: 1px solid lightgrey;">
{% endif %}
<div class="row row-items">
{% for object in object_list %}
<div class="{{ column_class|default:'col-xs-12 col-sm-4 col-md-3 col-lg-2' }}">
<div class="panel panel-primary panel-item">
<div class="panel-heading">
<div class="form-group" id="myform">
<div class="checkbox">
<label for="id_indexes_0">
{% if multi_item_actions %}
{% if multi_select_item_properties %}
<input class="form-multi-object-action-checkbox check-all-slave checkbox" type="checkbox" name="properties_{{ object|get_encoded_parameter:multi_select_item_properties }}" />
{% else %}
<input class="form-multi-object-action-checkbox check-all-slave checkbox" type="checkbox" name="{{ object.get_absolute_url }}" />
{% endif %}
{% endif %}
<span style="color: white; word-break: break-all; overflow-wrap: break-word;">
{% if not hide_object %}
{% if main_object %}
{% with object|object_property:main_object as object %}
{% if not hide_link %}<a name="test" href="{{ object.get_absolute_url }}">{{ object }}</a>{% else %}{{ object }}{% endif %}
{% endwith %}
{% else %}
{% if not hide_link %}{{ object }}{% else %}{{ object }}{% endif %}
{% endif %}
{% endif %}
</span>
</label>
</div>
</div>
</div>
<div class="panel-body">
{% if not hide_columns %}
{% for column in object|get_source_columns %}
<div class="text-center" style="">{% source_column_resolve column=column %}{{ column_result }}</div>
{% endfor %}
{% endif %}
{% for column in extra_columns %}
<div class="text-center"><span class="list-extra-column-label">{{ column.name }}</span>: {{ object|object_property:column.attribute }}</div>
{% endfor %}
{% if not hide_links %}
<p class="text-center">
{% get_menu_links 'object menu' source=object as resolved_links %}
{% for object_navigation_links in resolved_links %}
{% with 'true' as as_dropdown %}
{% include 'navigation/generic_navigation.html' %}
{% endwith %}
{% endfor %}
</p>
{% endif %}
</div>
</div>
</div>
{% empty %}
<div class="col-xs-12">
{% include 'appearance/no_results.html' %}
</div>
{% endfor %}
</div>
<!--</form>-->
{% include 'pagination/pagination.html' %}
</div>
</div>
</div>
<!--{% if object_list %}-->
<form method="post">
{% csrf_token %}
<input type="hidden" name="csrf-token" value="nc98P987bcpncYhoadjoiydc9ajD1cn">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3">
<button id="sendBTN" class="btn btn-success" type="submit">Send checked documents to another database</button>
</div>
<div class="col-md-3"></div>
</div>
</form>
<br>
<br>
<br>
<!--{% endif %}-->
<script type="text/javascript">
'use strict';
var $data = [];
$(document).on("click", "input[type='checkbox']", (e) => {
var name = $(e.target).attr("name");
if($(e.target).prop("checked")){
$data.push(name);
}else{
$data = jQuery.grep($data, function(value) {
return value != name;
});
}
console.log($data);
});
function csrfSafeMethod(method)
{
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if(!csrfSafeMethod(settings.type) && !this.crossDomain)
{
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
document.getElementById("sendBTN").onclick = function() {
var form_data = new FormData();
// form_data.append('file', $('#myform').get(0));
form_data.append('file', $data);
console.log(form_data);
$.ajax({
type: "POST",
// contentType: "application/x-www-form-urlencoded",
contentType : false,
processData: false,
url: "http://192.168.10.22:5000/api/FileRecive/GetDocument",
dataType: "json",
data: form_data,
success: function (data) {
data = $.parseJSON(data);
alert("success");
},
error: function (xhr) {
alert("error - " + xhr.statusText);
}
});
};
$(function() {
$('.row-items > [class*="col"] .panel-item .panel-heading').matchHeight();
$('.row-items > [class*="col"] .panel-item .panel-body').matchHeight();
$('.row-items > [class*="col"] .panel-item').matchHeight();
});
</script>
On the reciving side I am getting
name = "file"
value = "/documents/12/preview/"
But I want to get the file not this string. I have no idea how to target file to send it dirrectly.
The URL "/documents/12/preview/" is the URL to view the document using the user interface. If what you want is the actual file of the document, you need to use Mayan's API. Since documents in Mayan are a collection of versions, you need the ID of the latest version of the document you want. For this the API URL for the document detail which is:
"/api/documents/271/"
This will give you something like this:
From there look up the dictionary key "latest_version" and then the key "download_url". The download URL in the screenshot is "http://127.0.0.1:8000/api/documents/271/versions/267/download/". Do a GET request to this URL and you get the actual file of the document. Save the file in temporary variable (or Javascript Blob file object https://developer.mozilla.org/en-US/docs/Web/API/Blob) and then send it to your custom API with a POST request.
Another option is to just send the "download_url" to your API and have a worker process fetch the document data, that way you don't have to store the binary data of the document in the browsers memory.
For more information about Mayan's API go to "Tools" -> "API Documentation" and you'll get an API documentation view that allows testing the API with the live data in your installation.

Ajax error with django

I'm trying to activate add to the favorite button with ajax, also the same button should remove from favorite if it is already there, here is my full files:
models.py
class Favorite(models.Model):
item = models.ForeignKey(Item, on_delete='CASCADE')
user = models.ForeignKey(UserModel, on_delete='CASCADE')
class Meta:
unique_together = (('item', 'user'), )
urls.py
path('<int:pk>/favorite_item/', views.favorite_item, name='favorite_item'),
views.py
#login_required
def favorite_item (request, pk):
favitem = get_object_or_404(Item, pk=pk)
data = {
'is_fav': Favorite.objects.get(user=request.user, item=favitem).exists(),
}
if data ['is_fav']:
Favorite.objects.get(user=request.user, item=favitem).delete()
else:
new_entry = Favorite.objects.create(item=favitem, user=request.user)
return JsonResponse(data)
home.html
{% extends 'fostania_web_app/base.html' %}
{% block javascript %}
<script>
$("#add_to_fav").click(function () {
console.log( $(this).val() );
});
$.ajax({
url: form.attr("data-favorite_item-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_fav) {
alert('تم');
}
}
});
});
</script>
</script>
{% endblock %}
{% block content %}
{% load static %}
{% include 'fostania_web_app/slide.html' %}
<!-- Page Content -->
<div class="container">
<h1 class="my-4" align="right" dir="rtl">إستثمرى فساتينك القديمة مع Fostania</h1>
<!-- Marketing Icons Section -->
<div class="row">
<div class="col-lg-4 mb-4">
<div class="card h-100">
<h4 class="card-header" align="right">إنشاء حساب جديد</h4>
<div class="card-body">
<p class="card-text" align="center"><img src="{% static 'img/add_user_big.png' %}"><Br>
قم بإنشاء حساب جديد على فوستانيا حتى تستطيع عرض الفستان على الموقع</p>
</div>
<div class="card-footer" align="right">
تسجيل حساب جديد
</div>
</div>
</div>
<div class="col-lg-4 mb-4">
<div class="card h-100">
<h4 class="card-header" align="right">عرض الفستان على الموقع</h4>
<div class="card-body">
<p class="card-text" align="center"><img src="{% static 'img/plus_big.png' %}"><Br>
قم بإضافة الفستان مجاناً على الموقع حتى يصل الى مئات المشتريين و المهتمين
</p>
</div>
<div class="card-footer" align="right">
عرض الفستان على الموقع
</div>
</div>
</div>
<div class="col-lg-4 mb-4">
<div class="card h-100">
<h4 class="card-header" align="right">إبحثى عن الفستان المطلوب</h4>
<div class="card-body">
<p class="card-text" align="center"><img src="{% static 'img/search_big.png' %}"><Br>
او يمكن البحث عن الفستان المراد شرائه او تأجيره من وسط مئات الفساتين المعروضة</p>
</div>
<div class="card-footer" align="right">
إبدأ البحث
</div>
</div>
</div>
</div>
<!-- /.row -->
<!-- adsense -->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fostania-main -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-4202417439740489"
data-ad-slot="1170851377"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<!-- end -->
<!-- Portfolio Section -->
<h2 align="right"> اخر الفساتين المضافة للموقع</h2>
<div class="row">
{% for dress in dresss %}
<div class="col-lg-4 col-sm-6 portfolio-item">
<div class="card h-100" >
<img class="card-img-top" src="{{ dress.dress_image1.url }}" style='width: 200px;height: 200px;' alt="">
<div class="card-body">
<h4 class="card-title" align="center">
{% if user.is_authenticated %}
{% if user_favs %}
{% for item in user_favs %}
{% if item.item == dress %}
<a href="{% url 'favorite_item' dress.id %}" id="add_to_fav">
<img src="{% static 'img/star-yes.png' %}" title="مسح من الفساتين المفضلة"></a>
{% else %}
<a href="{% url 'favorite_item' dress.id %}" id="add_to_fav">
<img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a>
{% endif %}
{% endfor %}
{% else %}
<a href="{% url 'favorite_item' dress.id %}" id="add_to_fav">
<img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a>
{% endif %}
{% endif %}
{{ dress.dress_name }}
<Br>
<h3><span class="badge badge-warning">{{ dress.dress_price }} EGP</span></h3>
</h4>
<p class="card-text" align="right">
معروض {{ dress.dress_action }} <br>
فى محافظة {{ dress.dress_town }}
</p>
</div>
</div>
</div>
{% endfor %}
</div>
<!-- paginator part -->
<div align="right">
{% if dresss.has_previous %}
<button class="btn btn-success">« الأولى </button>
<button class="btn btn-success">السابقة</button>
{% endif %}
</div>
<div align="center">
<span class="current" >
صفحة رقم {{ dresss.number }} من إجمالى {{ dresss.paginator.num_pages }}
</span>
</div>
<div align="left">
{% if dresss.has_next %}
<button class="btn btn-success">التالية</button>
<button class="btn btn-success">الاخيرة »</button>
{% endif %}
</div>
<!-- paginator part ends -->
<hr>
<!-- Call to Action Section -->
<!-- /.container -->
{% endblock %}
And finally it gives me an error
DoesNotExist at /3/favorite_item/
Favorite matching query does not exist.
I made it as normal request which reloads when the user clicks it and it is working perfectly, but i need to Use Ajax to prevent the page from reloading.
If a Favorite doesn't exist for an Item, this will raise because you're using get(). get() raises if an object is not found: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#django.db.models.query.QuerySet.get
What I think you want is a combination of filter() and exists() like this:
data = {
'is_fav': Favorite.objects.filter(user=request.user, item=favitem).exists(),
}
i think that you need to use POST method for you ajax call
<script>
$("#add_to_fav").click(function () {
console.log( $(this).val() );
});
$.ajax({
url: form.attr("data-favorite_item-url"),
data: form.serialize(),
dataType: 'json',
method: 'POST', # <- here
...
});
});
</script>

Categories