I've got this system where I want to add in a favoriting feature where when someone clicks on the like button on a card it gets saved and displayed at port/wishlist.html but not able to go about and solve it, here is my Github Repository and some main codes.
models.py
from django.db import models
from django.contrib.auth.models import User
import datetime
YEAR_CHOICES = []
for r in range(1980, (datetime.datetime.now().year + 1)):
YEAR_CHOICES.append((r, r))
class Music(models.Model):
song = models.CharField(max_length=50, blank=False)
pic = models.ImageField(blank=False, null=True)
published_year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
description = models.CharField(max_length=80)
def __str__(self):
return self.song
class Wishlist(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,null=True)
music = models.ForeignKey(Music, on_delete=models.DO_NOTHING)
views.py
#login_required
def liked(request):
if request.method == "POST":
if user.is_authenticated:
# takes in the specific card id that is been liked and saves it and displays on Port/wishlist.html
music.save()
else:
return HttpResponse("Your card is Invalid")
else:
return HttpResponse("Your request is Invalid")
return render(request, template_name='main/wishlist.html', context={"wishlist": Wishlist.objects.all})
like.js
$(document).ready(function(){
$(".like").click(function(){
$(this).toggleClass("heart");
});
});
I would suggest doing something like this:
Here we create a new url for add to wishlist(add_to_wishlist). In like.js pass music_id through ajax with POST.If a user is login then show user's wishlisted product as heart symbol as red. And you can show wishlisted product through link in template. You can Understand all others in my code. Please try this. Thanks.
urls.py
from django.urls import path
from main import views
app_name = 'main'
urlpatterns = [
path('', views.home, name='home'),
path('signup/', views.signup, name='signup'),
path('wishlist/', views.liked, name='liked'),
path('login/', views.login_req, name='login'),
path('logout/', views.logout_req, name='logout'),
path('add-to-wishlist/', views.add_to_wishlist, name='add_to_wishlist'), # For add to wishlist
]
views.py
def home(request):
wishlisted_list =[]
if request.user.is_authenticated:
wishlisted_list = list(Wishlist.objects.filter(user_id=request.user).values_list('music_id',flat=True).order_by('music_id'))
return render(request, template_name='main/home.html', context={"music": Music.objects.all(),'wishlisted_list':wishlisted_list})
#login_required
def liked(request):
wishlist = {}
if request.method == "GET":
if request.user.is_authenticated:
wishlist = Wishlist.objects.filter(user_id_id=request.user.pk)
else:
print("Please login")
return HttpResponse("login")
return render(request, template_name='main/wishlist.html', context={"wishlist": wishlist})
#login_required
def add_to_wishlist(request):
if request.is_ajax() and request.POST and 'attr_id' in request.POST:
if request.user.is_authenticated:
data = Wishlist.objects.filter(user_id_id = request.user.pk,music_id_id = int(request.POST['attr_id']))
if data.exists():
data.delete()
else:
Wishlist.objects.create(user_id_id = request.user.pk,music_id_id = int(request.POST['attr_id']))
else:
print("No Product is Found")
return redirect("main:home")
like.js
$(document).ready(function(){
$(".like").click(function(){
var attr_id = $(this).attr('attr_id')
var action_url = $(this).attr('action_url')
var that = $(this)
$.ajax({
url: action_url,
type: "POST",
data: {'attr_id': attr_id },
headers: { "X-CSRFToken": $.cookie("csrftoken") },
success: function (result) {
console.log("Success")
that.toggleClass("heart");
},
error: function () {
alert("Please login");
}
});
});
});
home.html
{% load static %}
<link rel="stylesheet" href="{% static 'main/home.css' %}" type="text/css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Hey there,
{% if user.is_authenticated %}
<h1>{{user.username}}</h1>
{% else %}
<h1>unknown</h1>
{% endif %}
<a href="{% url 'main:liked' %}" >Wishlist</a>
<section class="cards">
{% for m in music %}
<div class="card">
<div class="top">
<div class="label1">{{m.song}}</div>
{% if m.pk in wishlisted_list %}
{% for i in wishlisted_list %}
{% if m.pk is i %}
<span class="like heart" id="id" attr_id="{{m.pk}}" action_url="{% url 'main:add_to_wishlist' %}"><i class="fa fa-heart"></i></span>
{% endif %}
{% endfor %}
{% else %}
<span class="like" id="id" attr_id="{{m.pk}}" action_url="{% url 'main:add_to_wishlist' %}"><i class="fa fa-heart"></i></span>
{% endif %}
</div>
<div class="middle">
<a href="https://google.com" id="link" target="_blank">
<div class="img-container"><img src="{{ m.pic.url }}"></div>
</a>
</div>
<a href="https://google.com" id="link" target="_blank">
<div class="bottom">
<div class="label4">{{m.description}}</div>
</div>
</a>
</div>
{% endfor %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="{% static 'main/js/like.js' %}" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</section>
wishlist.html
{% load static %}
<link rel="stylesheet" href="{% static 'main/home.css' %}" type="text/css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Hey there,
{% if user.is_authenticated %}
<h1>{{user.username}}</h1>
{% else %}
<h1>unknown</h1>
{% endif %}
<a href="{% url 'main:home' %}" >Go to Home</a>
<section class="cards">
{% if wishlist %}
{% for m in wishlist %}
<div class="card">
<div class="top">
<div class="label1">{{m.music_id}}</div>
<span class="like" id="id" attr_id="{{m.music_id.pk}}" action_url="{% url 'main:add_to_wishlist' %}"></span>
</div>
<div class="middle">
<a href="https://google.com" id="link" target="_blank">
<div class="img-container"><img src="{{ m.music_id.pic.url }}"></div>
</a>
</div>
<a href="https://google.com" id="link" target="_blank">
<div class="bottom">
<div class="label4">{{m.music_id.description}}</div>
</div>
</a>
</div>
{% endfor %}
{% else %}
<div class="card">
<div class="middle">
<div class="label1">Your Wishlist is empty...!</div>
</div>
<div class="bottom">
<div class="label4">Go to Shop</div>
</div>
</div>
{% endif %}
</section>
First things first, you need to add a primary key in the Music table assuming you name it as id
In the like.js file, you'll need to make an Ajax call to send the music ID to Django. Pass the music ID to the template when you render it so that you can pass it back during the Ajax call
like.js
$.ajax(path, {
data: {"music_id": 12345},
method: "POST",
success: function (data, textStatus, jqXHR) {
$(selector).toggleClass("heart");
},
error: function () {
console.log("Something went wrong");
}
Now, in you view, you can have something like this
view.py
def add_to_wishlist(request):
data = json.loads(request.body.decode("utf-8"))
user_id = request.user.id
music_id = data.get('domain_name'))
wishlist = Wishlist()
wishlist.user_id = user_id
wishlist.music_id = music_id
wishlist.save()
Related
I'm trying to implement infinite scroll with django and jquery(Waypoint).
I have a ListView with a pagination of 5, but when waypoint loads second page, AJAX requests are no longer performed so I added the AJAX function on the onAfterPageLoad which helps bring back AJAX function to the newly loaded page.
That's fine, but then it introduces a bug to my code making the page loaded initially (First Page) no longer perform AJAX functions very well. It makes AJAX on the first page run 3 times if I just loaded a third page and makes AJAX on the second page run twice and so on depending on the number of pages loaded already.
I don't know if there are any cool ways to achieve this because I tried using just jquery without waypoint, but still get same errors as I get when using just waypoint making it an error. This is kinda tricky so far.
{% extends "base.html" %}
{% block content %}
{% load static %}
<div class="container" style="max-width:700px">
<div class="px-3 pt-md-5 pb-md-4 mx-auto text-center">
<h1 class="display-4">All Groups</h1>
<p class="lead">List of groups</p>
</div>
<div class="">
<div class="row infinite-container">
{% for group in groups %}
<div class="col-md-12 infinite-item">
<!-- <img class="img-fluid" src="https://picsum.photos/700"> -->
<a class="text-dark" href="{{ group.get_absolute_url }}">
<div class="card mb-4 box-shadow">
<div class="card-body">
<h2 style="font-size:18px;font-weight:bold;min-height:42px;">
{{group.name|truncatechars:50}}</h2>
<div class="d-flex justify-content-between align-items-center">
<small class="text-muted">{{group.owner}}</small>
<small class="text-muted">{{group.date_created}}</small>
</div>
<p><a class='follow-btn' data-href='{{ group.get_group_follow_api_url }}'
data-likes='{{ page.likes.count }}'
href='{{ group.get_group_follow_url }}'>{{ group.follows.count }}
{% if request.user.profile in group.follows.all %}
Unfollow
{% else %}
Follow
{% endif %}
</a></p>
</div>
</div>
</a>
</div>
{% endfor %}
</div>
<!-- Comment for loading spinner -->
{% comment %}
<div class="d-flex d-none position-fixed" style="top:35vh;left:46vw">
<button class="btn btn-primary loading">
<span class="spinner-border spinner-border-sm"></span>
Loading...
</button>
</div>
{% endcomment %}
<!-- End of comment for loading spinner -->
<div class="row">
<div class="col-12">
{% if page_obj.has_next %}
<a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}"></a>
{% endif %}
</span>
</div>
</div>
</div>
</div>
<script src="{% static "js/jquery.waypoints.min.js" %}"></script>
<script src="/static/js/infinite.min.js"></script>
<script>
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0],
offset: 'bottom-in-view',
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function () {
$('.loading').hide();
$(document).ready(function(){
function updateText(btn, newCount, verb){
btn.text(newCount + " " + verb)
}
$(".follow-btn").click(function(e){
e.preventDefault()
var this_ = $(this)
var badge = this_.find('.unlike-update')
var followUrl = this_.attr("data-href")
var followCount = parseInt(this_.attr("data-follows")) | 0
var addFollow = followCount + 1
var removeFollow = followCount - 1
if (followUrl){
$.ajax({
url: followUrl,
method: "GET",
data: {},
success: function(data){
console.log(data)
var newFollows;
if (data.followed){
// updateText(this_, addLike, "Unlike")
// updateText(this_, data.likescount, badge)
updateText(this_, data.followscount, "Unfollow")
} else {
// updateText(this_, removeLike, "Like")
updateText(this_, data.followscount, "Follow")
// remove one like
}
}, error: function(error){
console.log(error)
console.log("error")
}
})
}
})
})
}})
</script>
{% include 'group/snippets/group_follow.html' %}
{% endblock %}
class GroupListView(LoginRequiredMixin, ListView):
model = Group
paginate_by = 5
context_object_name = 'groups'
template_name = 'group/group_list.html'
ordering = ['-date_created']
I'm trying to make an e-commerce site with Django and I'm stuck at my home page not being able to display which products are already in my cart. I am pretty sure I haven't got the JavaScript right but I'm an absolute beginner to web-dev so could also be the Python.
This is my home :
{% extends 'base.html' %}
{% block content %}
{% for pett in pets.all %}
<div class="row pt-3" onfocus="func(pett)">
<div class="col-8" onclick="window.location='{% url 'detail' pett.id %}';" style="cursor: pointer">
<h2>{{ pett.name }}</h2>
<h4>{{ pett.breed }}</h4>
</div>
<div class="col-4">
<a id="link{{pett.id}}" href= "javascript:{document.getElementById('add{{pett.id}}').submit()}"><button id="button{{pett.id}}" class='btn btn-primary btn-xs'><h1>Add to cart +</h1></button></a>
</div>
</div>
<form id="add{{pett.id}}" method="POST" action="{% url 'add_to_cart' pett.id %}">
{% csrf_token %}
<input type="hidden"/>
</form>
{% endfor %}
<script type="text/javascript">
function func(pett){
if(cart.objects.filter(pet=pett).count()>0) {
document.getElementById('button{{pett.id}}').innerHTML = "Added ✔︎";
document.getElementById('link{{pett.id}}').href = "";}
}
</script>
{% endblock %}
This is the call to my home method :
from django.shortcuts import render
def home(request):
pets = Pet.objects
if request.user :
cart = Cart.objects.get(buyer=request.user)
else:
cart=NULL
return render(request,'pets/home.html',{'pets':pets,'cart':cart})
This is my cart model :
from django.db import models
class Cart(models.Model):
buyer = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
pet = models.ManyToManyField('pets.Pet')
Everything else is working perfectly.
I have a Django application that accepts an Elasticsearch query in a form and produces a downloadable report. An earlier iteration worked great, but we decided to add a component that checks every ten seconds if the report is done being created. Our ultimate goal is to have it check repeatedly for the completed report (and tell the user the report is still processing if not complete), and then either add a button to download the report or just have it automatically begin downloading.
However, my application doesn't seem to be calling on the javascript block I have in my form.html. When I run this, it says {"file_created": False} until I manually refresh myself, then it switches to True. I tried the code commented out in check_progress (which is basically what my code in form.html does...) but it returned an error.
How do I make them communicate? What am I missing?
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
import os
import threading
from .forms import QueryForm
from .models import *
#login_required
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
query = form.cleaned_data["query"]
t = threading.Thread(target=generate_doc, args=(query,))
t.start()
return HttpResponseRedirect('/check_progress/')
else:
return HttpResponse("Your query does not appear to be valid. Please enter a valid query and try again.")
else:
form = QueryForm()
return render(request, 'audit_tool/form.html', {'form': form})
#login_required
def check_progress(request):
"""
Returns whether document generation is complete or in progress
"""
# check if file exists, return response as a JSON
# how to integrate with js code in html to continuously check and refresh
# only shows true when refreshed; how to talk to html??
file = "/report.docx"
data = {
"file_created": os.path.exists(file)
}
# if os.path.exists(file):
# response = generate_doc(query)
# return response
# else:
# return HttpResponseRedirect('/check_progress/')
# this does not work, "10.168.83.100 redirected you too many times.
# Try clearing your cookies.
# ERR_TOO_MANY_REDIRECTS"
return JsonResponse(data)
#login_required
def return_doc(request):
"""
Returns file response upon user request, or error message if something goes wrong
"""
response = generate_doc(query)
return response
form.html
<!-- templates/django_audit/form.html -->
{% extends 'base_login.html' %}
{% block javascript %}
<script>
var checkInterval = setInterval(isFileComplete, 10000); //10000 is 10 seconds
function isFileComplete() {
$.ajax({
url: '/check_progress/',
type: 'GET',
data: {
'file_created': 'True'
},
dataType: 'json',
success: function (data) {
if (data.exists) {
alert("Your file is ready to download!");
clearInterval(checkInterval);
} else {
alert("Your report is still being created, please hold.");
}
}
});
}
</script>
{% endblock %}
{% block title %}Form{% endblock %}
{% block content %}
<p><br></p>
<p><br></p>
<div class="alert alert-primary" role="alert">
<b>Instruction:</b>
{% load crispy_forms_tags %}
<!-- form action="/report/" method="post" onsubmit="this.submit(); this.reset(); return false; -->
<form action="/report/" method="post" onsubmit="this.submit(); this.reset(); return false;">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="Submit">
</form>
</div>
{% endblock %}
core/urls.py
from django.contrib import admin
from django.urls import include, path
from django.views.generic.base import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from audit_tool import views
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('form/', include('audit_tool.urls')),
path('report/', include('audit_tool.urls')),
path('check_progress/', views.check_progress, name='check_progress'),
path('', TemplateView.as_view(template_name='home.html'), name='home'),
] + static(settings.STATIC_URL, document_root=settings.STAT)
audit_tool/urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.get_query, name='form'),
] + static(settings.STATIC_URL, document_root=settings.STAT)
base_login.html
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<html lang="en">
{% load static %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
<link rel="shortcut icon" href="link/to/company/iconicon.ico" type="image/vnd.microsoft.icon" />
<title>Audit Report Tool</title>
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Dept</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="../">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../admin">Admin</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
<hr class="mt-0 mb-4">
<img src="{% static "logo.png" %}" alt="Company Logo" align="left"></img>
<img src="{% static "logo.png" %}" alt="Dept Logo" align="right" width="140" height="140"></img>
<h1 align="center"><font size="6"> Audit Report Tool</font></h1>
</div>
</div>
</div>
<body>
<main>
{% block content %}
{% endblock %}
</main>
</body>
</html>
Your key is data.file_created, not data.exists in if (data.exists) { line. And that sending of data: {'file_created': 'True'}, get rid of that in your javascript - you're not querying request for anything in your view, as, for example, the name of the file, so you don't need to fill that data.
Also the following:
file = "/report.docx"
data = {
"file_created": os.path.exists(file)
}
It implies that report.docx is going to be saved in the root of the filesystem, that's not going to happen. Use something like
from django.conf import settings
os.path.join(settings.BASE_DIR, "../upload/", "report.docx")
Also ,you may provide the part of base_login.html where that {% block javascript %} is placed.
The program open Bootstrap Modal and load Django Form to create new permission, this is works. But when i want in the form add new Ajax call to load dynamically elements in Django ChoiceField appears the error and browser not finish the call never.
I open browser inspect console and appears XMLHttpRequest error
url.py:
path('permisos/', general_views.permission_list,name='permission_list'),
path('permisos/crear', general_views.permission_create, name='permission_create'),
path('permisos/<int:id>/editar', general_views.permission_update, name='permission_update'),
path('permisos/<int:id>/detalle', general_views.permission_detail, name='permission_detail'),
path('permisos/<int:id>/borrar', general_views.permission_delete, name='permission_delete'),
path('permisos/crear/cargar_elementos/', general_views.permission_load, name='ajax_load_permissions'),
never get to call this function from ajax
views.py:
def permission_load(request):
type = request.GET.get('type')
if type == 2: # object
list = ['general', 'billing', 'accounting']
elements = ContentType.objects.filter(app_label__in=list)
elif type == 3: # instance
list = ['general', 'billing', 'accounting']
content_type = ContentType.objects.filter(app_label__in=list)
elements = general_models.content_type.model.objects.all()
elif type == 4: # attribute
list = ['general', 'billing', 'accounting']
content_type = ContentType.objects.filter(app_label__in=list)
elements = general_models.content_type.model.objects.all()
# get instance atributtes
else: # module
elements = general_models.Modules.objects.all()
# other aspect is that i dont know how to load view result in the html choicefield
response = { 'element': elements }
json = simplejson.dumps(response)
return HttpResponse(json, mimetype="text/json")
forms.py:
class CustomPermisisonForm(forms.Form):
name = forms.CharField()
ACTION_TYPE = ((1, ('Ver')),(2, ('Añadir')),(3, ('Modificar')),(4, ('Borrar')))
action = forms.MultipleChoiceField(choices=ACTION_TYPE, label='Acciones', initial=1, widget=forms.SelectMultiple())
PERMISSION_TYPE = ((1, ('Módulo')),(2, ('Objecto')),(3, ('Instancia')),(4, ('Atributo')))
type = forms.ChoiceField(choices=PERMISSION_TYPE, label='Tipo', initial=1, widget=forms.Select(attrs={"data-objects-url":"{% url 'ajax_load_permissions' %}"}))
element = forms.ModelChoiceField(queryset=general_models.Module.objects.all())
permissions.html:
{% block javascript %}
<script src="{% static 'js/permissions.js' %}"></script>
{% endblock %}
# this is the line to open modal
<button type="button" onclick="return openModalPermission('{% url 'general:permission_create' %}')" class="btn btn-outline-primary float-right btn-sm">
<span class="fas fa-plus"></span>
</button>
permission_create.html:
{% load static %}
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form method="POST" action="{% url 'general:permission_create' %}">
{% csrf_token %}
<div class="modal-header">
<h4 class="modal-title">Nuevo Permiso</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% include 'permission_form.html' %}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Crear</button>
</div>
</form>
</div>
</div>
# when comment this line the error disappear but don't work js call
<script src="{% static 'js/permissions.js' %}"></script>
permission_form.html:
{% load widget_tweaks %}
{% load static %}
{% for field in form %}
<div class="form-group{% if field.errors %} has-error{% endif %}">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{% render_field field class="form-control" %}
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
permissions.js:
function openModalPermission(url) {
$('#modal-permission').load(url, function() {
$(this).modal('show');
});
return false;
}
$("#id_type").change(function () {
console.log("js function");
var url = $("id_type").attr("data-objects-url");
var type = $(this).val();
console.log(type);
console.log(url);
$.ajax({
url: url,
data: {
'type': type
},
success: function (data) {
$("#id_element").html(data);
},
error: function (qXHR, textStatus, errorThrown) {
console.log(qXHR)
console.log(textStatus)
console.log(errorThrown)
}
});
return false;
});
Anybody know how to solve this problem ?
Thanks in advance.
SOLVED
permissions.html:
<!-- pass this block to the end of the file -->
{% block javascript %}
<script src="{% static 'js/permissions.js' %}"></script>
{% endblock %}
I've come across a strange bug in my Django application that has baffled me for the last few days.
Basically one of my dynamic templates stops rendering on the staging server. Everything works fine locally and when push to my staging server all seems fine however, after clicking around a few pages and then navigating back to one of the pages with this template it has suddenly disappeared. If i restart the supervisor processes the template reappears but then disappears again after navigating to other pages.
The weird thing is it's not consistent when it disappears. Sometimes it takes a few times navigating to other pages to disappear.
The template itself has dynamically generated content however even the container divs are not appearing so this leads me to believe that this is not a context error.
Another point about it is that if i stop my supervisor processes and run ./manage.py runserver instead, the problem doesn't seem to happen.
The things i've tried:
I've used django-template-repl to load the url and view the context
the template receives, all the data i expect to be rendered appears to be there.
Any help would be much appreciated, any tips on where to look next.
the view thats rendered:
def list(request):
projects = Project.objects.active()
order = request.GET.get('order', 'popular')
projects = projects.ordered_by(order)
search_q = request.GET.get('search_q')
if search_q:
project_query_terms = ['title', 'short_description', 'who_description']
username_query_terms = [
'user__userprofile__first_name',
'user__userprofile__last_name']
project_query = create_query(search_q, project_query_terms)
username_query = create_query(search_q, username_query_terms) & Q(
name_is_visible__exact=True)
projects = projects.filter(project_query | username_query)
if request.GET.get('sector'):
projects = projects.filter(sector__id=request.GET['sector'])
if request.GET.get('location'):
projects = projects.filter(
location=request.GET['location'],
location_public=True)
form = ProjectFilterForm
form = (form(request.GET, projects=projects)
if request.GET else form(projects=projects))
paginator = Paginator(projects, 9)
page = request.GET.get('page')
try:
projects = paginator.page(page)
except PageNotAnInteger:
projects = paginator.page(1)
except EmptyPage:
projects = paginator.page(paginator.num_pages)
amounts_by_project = Need.objects.amounts_by_project()
amounts_raised_by_project = MoneyDonation.objects.amounts_raised_by_project()
context = {
'body_id': 'project-list',
'projects': projects,
'form': form,
'order': order,
'amounts_by_project': amounts_by_project,
'amounts_raised_by_project': amounts_raised_by_project,
}
template = "_projects-content" if request.is_ajax() else "projects"
template = "projects/" + template + ".html"
return render(request, template, context)
the projects-projects.html template
{% extends 'projects/__base.html' %}
{% load image_tags staticfiles projects %}
{% block content %}
{% include 'projects/_projects-content.html' %}
{% endblock %}
{% block scripts %}
<script>
FCC.drawDonuts('.col-project');
jQuery(function updateWithFilters($){
function queryWithParams() {
var getParams = '';
$('#project-filter-form select').each(function(i) {
getParams += (i === 0) ? '?' : '&';
getParams += this.name + '=' + $(this).children('option:selected')[0].value;
});
$.get({% url 'projects' %} + getParams, function(res){
$("#projects-content").html(res);
updateWithFilters($);
FCC.drawDonuts('.col-project');
});
}
$('#project-filter-form select').change(function(e){
queryWithParams();
});
$('#reset-filters').click(function(e) {
e.preventDefault();
$('#project-filter-form select option:selected').each(function(){
$(this).prop('selected', false);
queryWithParams();
});
});
});
</script>
{% endblock %}
the _projects-content.html
<div id='projects-content'>
{% include 'projects/_projects-filters.html' %}
{% include 'projects/_projects-projects.html' %}
</div>
the _projects-projects.html
<section class="section hp-projects">
<div class="container">
<div class="row">
<div class="col-xs-12 sub-header">
<sub-header>
<h2>Browse all projects</h2>
</sub-header>
</div>
{% if not projects %}
<p>No projects match your search.</p>
{% endif %}
{% for project in projects %}
<div class="col-xs-12 col-sm-6 col-md-4">
{% include '_project-thumbnail.html' %}
</div><!--col-->
{% endfor %}
</div><!--row-->
<div class="row">
<div class="col-xs-12">
{% with projects as collection %}
{% include 'pagination.html' %}
{% endwith %}
</div>
</div>
</div><!--container-->
</section>
_project-thumbnail.html
{% load total staticfiles projects %}
<div class="project-container">
<header>
<a href="{% url 'project_detail' project.id %}" class="project">
<h5 class="project-title">{{ project.title }}</h5>
</a>
</header>
<figure>
<div class="img-wrap">
<a href="{% url 'project_detail' project.id %}" class="project">
<img class="img-responsive" src="{{ MEDIA_URL }}{{ project.profile_image }}" alt="project image" />
</a>
</div>
<figcaption>{{ project.short_description }}</figcaption>
</figure>
<div class="row three-donuts">
<div class="col-xs-6">
{% include "projects/_project-donate-thumbnail.html" %}
</div>
<div class="col-xs-6">
{% include "projects/_project-volunteer-thumbnail.html" %}
</div>
</div>
</div><!--box-container-->
_project-donate-thumbnail.html is the template that is not rendering after navigating to another page
here's the content of the file but as i said nothing inside this renders once you navigate away from this page after a fresh server restart.
however the _project-volunteer-thumbnail stays completely fine. It is just the donate-thumnail that disappears.
_project-donate-thumbnail.html
<div id="project-{{ project.id }}-donate" class="col-project this-project-donate">
<span class="percentage">
{% if project.donate_aim %}
{{ project.donate_percent }}%
{% endif %}
</span>
</div>
<div class="equation">
£{{ project.donate_status }}
<span class="desired-amount">/ £{{ project.donate_aim }}</span>
</div>
<div class="button-link-wrapper">
{% if project.donate_aim %}
donate
{% else %}
<span class="button graph-button donate deactivated">donate</span>
{% endif %}
</div>
again any tips on where to look next would be helpful