I got this model:
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
item = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField()
and I'd like to make user able to change its quantity value without reloading page
tried to do it this way:
views:
def increaseQuantity(request):
if request.method == 'GET':
orderItem_id = request.GET['orderItem_id']
orderitem = OrderItem.objects.get(id=orderItem_id)
orderitem.quantity += 1
orderitem.save()
url
path('cart/increase/', increaseQuantity, name='increase'),
template:
{% for product in products %}
<div >Some button content</div>
{% endfor %}
#
#
#
$('.quantity-increase').click(function(){
var orderItemId;
orderItemId = $(this).attr("data-orderItemId");
$.ajax({
type: "GET",
url: "increase",
data:{
orderItem_id:orderItemId
},
})
})
Quantity is being increased correctly, but I need to reload page to see results. What should I add/change to be allowed to see them without reloading ?
view used to see results:
def cart(request):
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
context = {'items':items, 'order':order, 'cartItems':cartItems}
return render(request, 'store/cart.html', context)
template
{% for item in items %}
<div class="cart-row">
<div style="flex:2"><img class="row-image" src="{{ item.product.imageURL }}"></div>
<div style="flex:2">{{ item.product.name }}</div>
<div style="flex:1">${{ item.product.price|floatformat:2 }}</div>
<div style="flex:1">
<p class = "quantity">{{item.quantity}}</p>
<div class = "quantity">
<img data-product={{item.product.id}} data-action="add" class="chg-quantity update-cart" src="{% static 'images/arrow-up.png' %}">
<img data-product={{item.product.id}} data-action="remove" class="chg-quantity update-cart" src="{% static 'images/arrow-down.png' %}">
</div>
</div>
<div style="flex:1">${{ item.get_total }}</div>
</div>
{% endfor %}
POST method is more suitable for this request
view
from django.http import JsonResponse
def increaseQuantity(request):
if request.method == 'POST':
if request.POST.get("operation") == "increase":
orderitem = OrderItem.objects.get(id=request.POST.get('orderItem_id', None))
orderitem.quantity += 1
orderitem.save()
return JsonResponse({'count':orderitem.quantity)
return JsonResponse({'error':'error')
html
{% for product in products %}
<div >Some button content</div>
{% endfor %}
#
#
#
$('.quantity-increase').click(function(){
var orderItemId;
orderItemId = $(this).attr("data-orderItemId");
$.ajax({
type: "POST",
url: "increase",
data:{
orderItem_id:orderItemId,
csrfmiddlewaretoken: '{{ csrf_token }}',
'operation':'increase'
},
success: function(data) {
$('.count-of-item').html(data.count) // your results element to show current quantity
console.log(data.count)
},
})
})
Related
hello I have a post model which has a like(m2m) and user(forgeinkey) model field and Im trying to check if the request.user has liked the post and if they have, I should show them a red heart button else a blue heart should be shown, now since there are multiple posts and likes, Im looping through each like object to check if the request.user has liked it or not. Unfortunately for some reason, I couldn't implement a good logic and I see like button for every user. Some help would be appreciated.
Here's my model:
class post(models.Model):
user = models.ForeignKey(User,default='' , related_name='has_liked', on_delete=models.CASCADE)
caption = models.CharField(max_length=100)
image = models.FileField(upload_to='images/', null=True, blank=True)
video = models.FileField(upload_to='videos/', null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
like = models.ManyToManyField(User, null=True, blank=True, default='')
The View:
#login_required
def usersfeed(request):
users = User.objects.all()
posts = post.objects.filter(Q(user__in=request.user.profile.friend.all()) | Q(user=request.user)).order_by('-created')
comments = Comment.objects.all()
status_form = StatusForm(request.POST)
friend_requests = FriendRequest.objects.filter(to_user=request.user)
friends = request.user.profile.friend.all()
for i in posts:
likes = i.like.all()
print(likes)
for like in likes:
if like.username == request.user.username:
if request.user:
Hasliked = True
print('liked')
else:
Hasnotliked = True
print('not liked')
context = {
'Post':posts,
'User':users,
'form':PostForm(),
'Profile':profile,
'Form':CommentForm(),
'Comment':comments,
'Status':status_form,
'fr':friend_requests,
'friend':friends,
'Hasliked':Hasliked,
'Hasnotliked':Hasnotliked,
}
return render(request, 'social_media/feed.html', context=context)
The view for ajax like counter:
#login_required
def like_post(request):
Post = get_object_or_404(post, id=request.GET.get('post_id'))
cssClass = 'colorRed'
if Post.like.filter(id=request.user.id).exists():
Post.like.remove(request.user)
else:
Post.like.add(request.user)
count = Post.like.count()
users = Post.like.all()
user = []
for i in users:
user.append((i.username))
response = {
'count':count,
'users':user,
'cssClass':cssClass,
}
return JsonResponse(response)
The Html code:
{% for i in Post %}
<form action="{% url 'like_post' %}" class='like-submit' data-catid="{{ i.id }}" method="GET">
<div class="like">
{% if Hasliked == True %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn colorRed">
<i class="fas fa-heart"></i>
</button>
{% endif %}
{% if Hasnotliked == True %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn">
<i class="fas fa-heart"></i>
</button>
{% endif %}
<div class="show_likes">
<span id="likes_count{{ i.id }}">{{ i.total_likes }}</span>
<div class="username_liked">
<div id="user-likes{{ i.id }}" class="user-likes">
{% for p in i.like.all %}
{{ p.username }}
{% endfor %}
</div>
</div>
</div>
</div>
</form>
{% endfor %}
<script>
$(document).ready(function () {
$(".like-submit").submit(function (event) {
event.preventDefault()
const url = $(this).attr('action');
const catid = $(this).attr("data-catid");
$.ajax({
type: "GET",
url: url,
data: {
post_id: catid,
},
success: function (data) {
$('#likes_count' + catid).html(data.count)
if ($('#user-likes' + catid).html()){
$('#user-likes' + catid).html(data.users + ' ')
$('#likeBtn' + catid).toggleClass(data.cssClass)
}
}
});
});
});
</script>
you need to store the hasLiked/hasNotLiked in the post record for that user. The code above, implies that all posts are either liked or unliked. You also need to rethink the way you load your context- the current code is extremely inefficient. I would suggest to replace the Hasliked and Hasnotliked context entries with id arrays where each one will contains the ids of the posts that the current user liked/disliked. Then in the template do in check:
{% if i.id in Hasliked %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn colorRed">
<i class="fas fa-heart"></i>
</button>
{% endif %}
{% if i.id in Hasnotliked %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn">
<i class="fas fa-heart"></i>
</button>
{% endif %}
the hasliked, disliked can be loaded using your current setup:
friends = request.user.profile.friend.all()
for i in posts:
likes = i.like.all()
print(likes)
for like in likes:
if like.username == request.user.username:
if request.user:
Hasliked.append(i.id)
print('liked')
else:
Hasnotliked.append(i.id)
print('not liked')
This it would be extremely inefficient, the best way to si ur is to query the database directly, and simply returning the ids:
l_likedPosts = PostActions.objects.filter(user_id=l_currUser,
liked=True)
.values_list('post_id',flat=True)
Hasliked = list(l_likedPosts)
The code above assumes that you have a table PostActions that contains at least the user_id, the post_id and the liked/disliked status. This is generally what the manytomany field does for you, behind the scenes, but using it takes too much freedom in more complicated data models.
I have a form that I am trying to implement with Ajax, after inputing some content on the textbox, when I click on the sumbit button using my mouse, everything works fine (page didnt refresh, data posted on database, and new data displayed on the page). But when I try to submit data by pressing enter, the page is displaying only the serialized data from my form (nothing more, html file do not work)and it says in the console:
Resource interpreted as Document but transferred with MIME type application/json: "http://localhost:8000/try/".
current page looks exactly like this after pressing enter button(nothing more):
{"task": {"id": 52, "todo": "wws", "author": 1, "completed": false}}
these are the data that came from my form.
this is my views.py
class TodoList(View):
def get(self, request):
todo_list = ToDo.objects.filter(author_id=request.user.id)
form = AddTodo()
context = {
'todo_list': todo_list,
'form': form,
}
return render(request, 'trylangto/try.html', context)
def post(self, request):
form = AddTodo(request.POST)
if form.is_valid():
form.instance.author_id = request.user.id
new_form = form.save()
return JsonResponse({'task': model_to_dict(new_form)}, status=200)
else:
return redirect('trylang:todo-list')
return redirect('trylang:todo-list')
this is my main.js:
$(document).ready(function(){
$("#createbutton").click(function(){
var formdata = $("#addtodoform").serialize();
$.ajax({
url: $("#addtodoform").data('url'),
data: formdata,
type: 'post',
success: function(response){
$("#tasklist").append('<div class="card mb-1" ><div class="card-body">'+ response.task.todo +'<button type="button" class="close"><span aria-hidden="true">×</span></button></div></div>')
}
});
});
});
and here is my template:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
{% if user.is_authenticated %}
<div class="media content-section">
<form class="media-body pt-3" method="POST" id="addtodoform" data-url="{% url 'trylang:todo-list' %}">
{% csrf_token %}
<legend><h5>add new tasks</h5></legend>
<fieldset class="form-group ">
{{ form|crispy}}
</fieldset>
<button class="btn btn-outline-info float-right" type="button" id="createbutton">add</button>
</form>
</div>
{% endif %}
<div id="tasklist">
{% for task in todo_list %}
<div class="card mb-1" >
<div class="card-body">
{{task.todo}}
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
UPDATE: I am including my models.py just in case
class ToDo(models.Model):
todo = models.CharField(max_length=500)
date_posted = models.DateTimeField(default=timezone.now, editable=False)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
completed = models.BooleanField(default=False)
this is what I get on the console when I use console.log(formdata):
csrfmiddlewaretoken=N91OUGSd6kBFkB1E2DMZuMW6qJD7cc3frPprwGMLTuupcg6PKYtt44jA4z5Lx6xX&todo=this%20is%20the%20content%20of%20my%20textbox
You don't need model_to_dict. So, try:
if form.is_valid():
form.instance.author_id = request.user.id
new_form = form.save()
return JsonResponse({'task': new_form}, status=200)
else:
return redirect('trylang:todo-list')
return redirect('trylang:todo-list')
EDIT
You are submitting the form not through ajax. When you click button it was submitting the form. So, e.preventDefault() should do the job.
$(document).ready(function(){
$("#createbutton").click(function(e){
e.preventDefault(); <--- You were missing this
var formdata = $("#addtodoform").serialize();
$.ajax({
url: $("#addtodoform").data('url'),
data: formdata,
type: 'post',
success: function(response){
$("#tasklist").append('<div class="card mb-1" ><div class="card-body">'+ response.task.todo +'<button type="button" class="close"><span aria-hidden="true">×</span></button></div></div>')
}
});
});
});
So I have a model called Organization inside core/models.py. I am trying to implement CRUD Ajax on a single page. Inspired by this post. Every time I save an object of this model I get this error as shown below. I want to have multiple organizations that are unique.
core/models.py
class Organization(models.Model):
name = models.CharField(max_length=255, unique=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
gstin = models.CharField(max_length=15)
address = models.CharField(max_length=500)
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zipcode = models.CharField(max_length=6)
country = models.CharField(max_length=50)
is_billed = models.BooleanField(default=False)
def __str__(self):
return f'{self.name} Organization'
core/forms.py
class OrganizationForm(forms.ModelForm):
class Meta:
model = models.Organization
fields = ('name', 'address', 'state', 'city', 'zipcode', 'country', 'gstin')
core/views.py
def save_organization_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
stock = form.save(commit=False)
stock.user = request.user
stock.save()
data['form_is_valid'] = True
organizations = Organization.objects.all()
data['html_book_list'] = render_to_string('core/includes/partial_organization_list.html', {
'organizations': organizations
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
#login_required(login_url="/accounts/login/")
def organization_create(request):
if request.method == 'POST':
form = OrganizationForm(request.POST)
else:
form = OrganizationForm()
return save_organization_form(request, form, 'core/includes/partial_organization_create.html')
templates/base.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>{% block head_title %}{% endblock %}</title>
{% block extra_head %}
{% endblock %}
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Russo One' rel='stylesheet'>
<link rel="stylesheet" type="text/css" href="{% static 'font/flaticon.css' %}">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
{% block body %}
{% if messages %}
<div class="text-center">
<strong>Messages:</strong>
<ul>
{% for message in messages %}
<li>{{message}}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% block content %}
{% endblock %}
{% endblock %}
{% block extra_body %}
{% endblock %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
{% block javascript %}
{% endblock %}
</body>
</html>
templates/core/organization_list.html
{% extends 'base.html' %}
{% load static %}
{% block javascript %}
<script src="{% static 'organizations/js/organizations.js' %}"></script>
{% endblock %}
{% block content %}
<h1 class="page-header">Organizations</h1>
<!-- BUTTON TO TRIGGER THE ACTION -->
<p>
<button type="button"
class="btn btn-primary js-create-book"
data-url="{% url 'organization_create' %}">
<span class="glyphicon glyphicon-plus"></span>
New Organization
</button>
</p>
<table class="table" id="book-table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Address</th>
<th>State</th>
<th>City</th>
<th>Zipcode</th>
<th>Country</th>
<th>Billing Active</th>
</tr>
</thead>
<tbody>
{% include 'core/includes/partial_organization_list.html' %}
</tbody>
</table>
<!-- THE MODAL WE WILL BE USING -->
<div class="modal fade" id="modal-book">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
{% endblock %}
templates/core/partial_organization_list.html
{% for organization in organizations %}
<tr>
<td>{{ organization.id }}</td>
<td>{{ organization.name }}</td>
<td>{{ organization.address }}</td>
<td>{{ organization.state }}</td>
<td>{{ organization.city }}</td>
<td>{{ organization.zipcode }}</td>
<td>{{ organization.country }}</td>
<td>{{ organization.is_billed }}</td>
<td>
<button type="button"
class="btn btn-warning btn-sm js-update-book"
data-url="{% url 'organization_update' organization.id %}">
<span class="glyphicon glyphicon-pencil"></span> Edit
</button>
<button type="button"
class="btn btn-danger btn-sm js-delete-book"
data-url="{% url 'organization_delete' organization.id %}">
<span class="glyphicon glyphicon-trash"></span> Delete
</button>
</td>
</tr>
{% empty %}
<tr>
<td colspan="8" class="text-center bg-warning">No Organization</td>
</tr>
{% endfor %}
static/organizations/js/organizations.js
$(function () {
$(".js-create-book").click(function () {
$.ajax({
url: '/profile/organization/create/',
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
});
$("#modal-book").on("submit", ".js-book-create-form", function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#book-table tbody").html(data.html_book_list); // <-- Replace the table body
$("#modal-book").modal("hide"); // <-- Close the modal
}
else {
$("#modal-book .modal-content").html(data.html_form);
}
}
});
return false;
});
$(".js-create-book").click(function () {
var btn = $(this); // <-- HERE
$.ajax({
url: btn.attr("data-url"), // <-- AND HERE
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
$(function () {
/* Functions */
var loadForm = function () {
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
};
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#book-table tbody").html(data.html_book_list);
$("#modal-book").modal("hide");
}
else {
$("#modal-book .modal-content").html(data.html_form);
}
}
});
return false;
};
/* Binding */
// Create book
$(".js-create-book").click(loadForm);
$("#modal-book").on("submit", ".js-book-create-form", saveForm);
// Update book
$("#book-table").on("click", ".js-update-book", loadForm);
$("#modal-book").on("submit", ".js-book-update-form", saveForm);
// Delete book
$("#book-table").on("click", ".js-delete-book", loadForm);
$("#modal-book").on("submit", ".js-book-delete-form", saveForm);
});
And when I add a new organization I get the following error:
django.db.utils.IntegrityError: UNIQUE constraint failed: core_organization.name
How do I fix this?
I believe your javascript file contains duplicate ajax calls.
There are 3 calls to create your modal:
$(function () {
$(".js-create-book").click(function () {
at the top of your js file. Then the same function in the middle of your js file. And
var loadForm = function ()
which your binding to the click event at the bottom of your script.
In addition there are two functions handling the submission of the form data:
$("#modal-book").on("submit", ".js-book-create-form", function ()
in the top part and
var saveForm = function ()
in the bottom part.
The duplicate regarding the submission of the form can cause the unique constraint error because you are submitting the same data twice. The duplication of the loading of the modal probably does not cause any noticable errors, but is unnecessary load.
The bottom part of your javascript file, i.e. the part beginning with
$(function () {
/* Functions */
should be sufficient.
I think you are having this issue, because of the unique=True constraint on your name field
name = models.CharField(max_length=255, unique=True)
This means that the name is going to be unique for all users, and you will keep getting UNIQUE constraint failed error everytime you add the same name for different users.
To solve this, I suggest using unique_together meta option.
All you have to do, is removing the unique constraint from name field, and adding Meta class with the unique_toghether option to include both the user_id and name fields.
class Organization(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey(User, on_delete=models.CASCADE)
address = models.CharField(max_length=1000, default=None)
is_billed = models.BooleanField(default=False)
def __str__(self):
return f'{self.name} Organization'
class Meta:
unique_together = ['name', 'user_id']
Then, python manage.py makemigrations, python manage.py migrate.
The UNIQUE constraint going to remain, but it is going to be for all Organization names related for one user.
If USER1 have organization ORG1, and tried to add another ORG1, it is going to fail, but if USER2 added ORG1 it is going to work successfully.
Try updating the instance rather than form object, Create separate endpoint/logic for updating instance and an separate endpoint/logic to create objects using form
views.py
def save_organization_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
stock = form.instance
stock.user = request.user
stock.something = request.something
stock.save()
data['form_is_valid'] = True
organizations = Organization.objects.all()
data['html_book_list'] = render_to_string('core/includes/partial_organization_list.html', {
'organizations': organizations
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
#login_required(login_url="/accounts/login/")
def organization_create(request):
if request.method == 'POST':
form = OrganizationForm(request.POST)
else:
form = OrganizationForm()
return save_organization_form(request, form, 'core/includes/partial_organization_create.html')
I have endless pagination working on my site for posts.
Each post has a like and dislike button which works using ajax.
The first set of posts have working buttons but all posts delivered with pagination don't have working buttons. When clicking the buttons they don't even run the ajax to send a query to my views.py file but the first set of posts have working ones.
urls.py
path("likepost/", user_views.like_post_view, name='like_post'),
path("dislikepost/", user_views.dislike_post_view, name='dislike_post'),
views.py file
sort = request.GET.get("sort")
if sort=="newest":
posts = Post.objects.filter(deleted=False).order_by('-date_posted')
sort_type = "newest"
if sort=="oldest":
posts = Post.objects.filter(deleted=False).order_by('date_posted')
sort_type = "oldest"
if sort=="top-alltime":
posts = Post.objects.filter(deleted=False).annotate(like_count=(Count('like_post')-Count("dislike_post"))).order_by('-like_count')
sort_type = "top-alltime"
if sort==None or sort=="top-today":
today = datetime.now().date()
today_start = datetime.combine(today, time())
posts = Post.objects.filter(deleted=False, date_posted__gte=today_start).annotate(like_count=(Count('like_post')-Count("dislike_post"))).order_by('-like_count')
sort_type = "top-today"
if sort=="top-week":
current_week = date.today().isocalendar()[1]
posts = Post.objects.filter(deleted=False, date_posted__week=current_week).annotate(like_count=(Count('like_post')-Count("dislike_post"))).order_by('-like_count')
sort_type = "top-week"
page = request.GET.get('page', 1)
paginator = Paginator(posts, 4)
trending_tags = Post.tags.most_common()[:5]
try:
posts_given = paginator.page(page)
except PageNotAnInteger:
posts_given = paginator.page(1)
except EmptyPage:
posts_given = paginator.page(paginator.num_pages)
context = {
"trending_tags": trending_tags,
"posts_given": posts_given,
"sort": sort_type
}
return render(request, "users/index.html", context)
#login_required
#require_GET
def like_post_view(request):
print("LIKE REQUESTED!!!!!!!!!!!!!")
if request.method == 'GET':
user = request.user
user = User.objects.get(username=user)
post_id = request.GET.get('post_id', None)
post = Post.objects.get(id=post_id)
if like_post.objects.filter(user=user, post=post).exists():
# user has already liked this post
# remove like/user
like_post.objects.filter(user=user, post=post).delete()
#return -1
return HttpResponse(-1)
else:
# add a new like for the post
like_post.objects.create(post=post, user=user)
if dislike_post.objects.filter(user=user, post=post).exists():
dislike_post.objects.filter(user=user, post=post).delete()
return HttpResponse(+2)
return HttpResponse(+1)
#login_required
#require_GET
def dislike_post_view(request):
print("DISLIKE REQUESTED!!!!!!!!!!!!!")
if request.method == 'GET':
user = request.user
user = User.objects.get(username=user)
post_id = request.GET.get('post_id', None)
post = Post.objects.get(id=post_id)
if dislike_post.objects.filter(user=user, post=post).exists():
# user has already disliked this post
# remove dislike/user
dislike_post.objects.filter(user=user, post=post).delete()
return HttpResponse(+1)
else:
# add a new dislike for the post
dislike_post.objects.create(post=post, user=user)
if like_post.objects.filter(user=user, post=post).exists():
like_post.objects.filter(user=user, post=post).delete()
return HttpResponse(-2)
return HttpResponse(-1)
template
{% load static %}
{% block content %}
<h1>Homepage</h1>
<div class="infinite-container" id="infinite-container" style="max-width:700px;width:100%;margin-left:auto;margin-right:auto;">
<form action="/action_page.php">
{% csrf_token %}
<div style="display:inline-block;">
<h5 style="margin-left:10px;">Sort by</h5>
<select name="sort" class="sort_by" id="sort_by" style="margin-left:10px;">
<option value="newest">Newest</option>
<option value="top-today" selected="selected">Top Today</option>
<option value="top-week">Top This Week</option>
<option value="top-alltime">Top All Time</option>
<option value="oldest">Oldest</option>
</select>
</div>
</form>
{% for post in posts_given %}
<div class="post infinite-item" style="background-color:#494a4d;border-radius: 8px; color: white;padding:10px;margin:10px;">
<h2>{{ post.title }}<h2>
<hr>
<img src="/uploads/{{ post.image }}" alt="{{ post.image }}" style="max-width:100%; max-height:500px;">
<hr>
<div class="row-post">
<div class="column-post-left">
<h4 style="text-align: left;">by {{ post.user.username }} | {{ post.date_posted | timesince }} ago {% if request.user.is_authenticated and post.user == request.user %} | edit{% else %} | report{% endif %}</h4>
<h5 style="word-wrap: break-word;word-break: break-word;">{% for tag in post.tags.all %} #{{ tag }}{% endfor %}</h5>
<h5>{{ post.comment_count }} comments</h5>
</div>
<div class="column-post-right">
<input src="{% static "memeplaza/rocket_white.png" %}" type="image" style="max-width:50px;max-height:50px;" class="like" name="{{ post.id }}" value="Like"/>
<p style="font-size:22px;" id="{{ post.id }}">{{ post.like_count }}</p>
<input src="{% static "memeplaza/flash_white.png" %}" style="max-width:50px;max-height:50px;" type="image" class="dislike" name="{{ post.id }}" value="Dislike" />
</div>
</div>
</div>
{% endfor %}
</div>
{% if posts_given.has_next %}
<a class="infinite-more-link" href="?sort={{ sort }}&page={{ posts_given.next_page_number }}"></a>
{% endif %}
<script>
var infinite = new Waypoint.Infinite({element: $('.infinite-container')[0]});
$('.sort_by').change(function(){
var sort_type = $('#sort_by :selected').val();
window.location = "/?sort="+sort_type;
})
$('.like').click(function(){
var id = $(this).attr('name');
console.log("Like button pressed!");
$.ajax({
type: "GET",
url: "{% url 'like_post' %}",
data: {'post_id': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response){
var score = $("#" + id).text();
score = score.split(" ")[0];
score = parseInt(score) + parseInt(response);
$("#" + id).text(score);
}
});
})
$('.dislike').click(function(){
var id = $(this).attr('name');
console.log("disLike button pressed!");
$.ajax({
type: "GET",
url: "{% url 'dislike_post' %}",
data: {'post_id': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response){
var score = $("#" + id).text();
score = score.split(" ")[0];
score = parseInt(score) + parseInt(response);
$("#" + id).text(score);
}
});
})
</script>
{% if sort is not empty %}
<script>
$(document).ready(function(){
$("#sort_by").val("{{ sort }}");
});
</script>
{% endif %}
{% endblock content %}```
You should use $('selector').on for binding events to elements that do not exist yet
$('#infinite-container').on('click', '.like', function() {
...
})
$('#infinite-container').on('click', '.dislike', function() {
...
})
Using $('.like').click will only bind the event handler to elements that currently exist on the page
I am using the rest frame in my django app in order to access some data.
For some reason, I do not manage to access it. I have no error message but the data is not showing up.
my views are.
class TeamChartData(APIView):
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer, #ProjectSerializer
permission_classes = []
http_method_names = ['get',]
def get_serializer_class(self):
return self.serializer_class
def get(self, request, format=None, *args, **kwargs):
cohesiveness_score = get_team_cohesivenss_score(self)
data = {
"cohesiveness_score":cohesiveness_score[0],
}
return Response(data)
my Html :
{% extends 'base.html' %}
{% load static %}
{% block body %}
<div class="container paddingtop80 marginbottom30">
<div class="row">
{% if project.has_member_responses %}
<div class="col-8">
<div class="jumbotron greenback">
<h4>Welcome to the Project test "{{ project.name }}" Detail page</h4>
</div>
</div>
<div class="col-4">
<div class="jumbotron greenback">
<div class="inner-score">
<h6>Team Score</h6>
<h4>{{cohesiveness_score}}</h4>
</div>
</div>
</div>
{% else %}
<div class="col">
<div class="jumbotron greenback">
<h4>Welcome to the Project "{{ project.name }}" Detail page</h4>
</div>
</div>
{%endif%}
</div>
<!-- case 1 = if there is not team created or linked -->
{% if project.team_id == None %}
{% include "projectdetailtemp/noteamcreated.html" %}<
<!-- case 2 = if there is a team created but no team members -->
{% elif project.team_id and project.team_id.members.count == 0 %}
{% include "projectdetailtemp/teamnomember.html" %}<
<!-- any other situation -->
{% else %}
{% include "projectdetailtemp/other.html" %}
{% endif %}
{% if project.has_member_responses %}
{% include "survey/team_dashboard.html" %}
{% else %}
<div class="jumbotron redback">
We are still waiting for all members to answer the team questionnaire
</div>
{% endif %}
</div>
{% endblock%}
<script>
var endpoint = 'api/chart/data2'
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
cohesiveness_score = data.cohesiveness_score
}
})
</script>
when I go to my endpoint I can see the data that I am trying to access to the problem does not come from the view.py I guess..
The data I am trying to access is :{{cohesiveness_score}}
Could someone help me ?
edited:
the view in question :
def TeamSelect(request):
#import pdb; pdb.set_trace()
if request.method == "POST":
select_form = EditSelectTeam(request.user, request.POST)
if select_form.is_valid():
data = select_form.cleaned_data['team_choice']
obj2 = Project.objects.filter(project_hr_admin=request.user)
obj3 = obj2.latest('id')
if obj3.team_id == None:
obj3.team_id = data
obj3.save()
obj4 = obj3.team_id
obj5 = obj4.members.all()
for i in obj5:
current_site = get_current_site(request)
message = render_to_string('acc_join_email.html', {
'user': i.first_name,
'domain':current_site.domain,
})
mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
to_email = i.email
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
messages.success(request, 'test')
return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':obj3.id}))
else:
print('this project has already a team')
else:
print('Non Valid form')
else:
select_form = EditSelectTeam(request.user)
return render(request,'link_project.html',
{'select_form':select_form })
the url :
url(r'^project/(?P<pk1>[0-9]+)/linkteam2/$', views.TeamSelect, name='team_select'),
the link :
<span class="fa fa-link"></span> Link an existing team
By default rendering class of Views in Django rest is JSONRenderer. You need to define your rendering class to HTML and template name. After this, yiur data will be rendered in HTML.
from rest_framework.renderers import TemplateHTMLRenderer
class TeamChartData(APIView):
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer, #ProjectSerializer
permission_classes = []
http_method_names = ['get',]
renderer_classes = [TemplateHTMLRenderer]
template_name = 'template_name.html'