Django App Not Communicating with JavaScript Code Block - javascript

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.

Related

Flask repeating function by keep pressing a button

today I've been trying to resolve this problem, but I can't figure it out how to "fix".
I'm creating a website using Flask, and when I'm clicking a button placed in a post form, I'd like to keep an action doing; to be more accurate, when I click the button, an action should be performed, but I'd like this action to be performed more times if I keep pressing the button. This is the structure of my layout and code.
Here is the python code
from flask import (
Blueprint, render_template, request
)
from webapp.Utilities.utilities import SerialHandler
from webapp.blueprints.decorators import login_required
bp = Blueprint('main', __name__)
serial_scheduler = SerialHandler()
#bp.route('/', methods=('GET', 'POST'))
#login_required
def index():
if request.method == 'POST':
button = request.form['press_to_run']
foo()
return render_template('index.html', title="Index")
And here the HTML structure
{% extends "layout.html" %}
{% block stylesheet %}
<link rel="stylesheet" href="{{ url_for('static', filename='index.css') }}">
{% endblock %}
{% block content %}
<div class="container new_container">
<div class="card" style="width: 18rem;">
<div class="card-header">
Featured
</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>
</div>
<div class="container">
<img src="{{ url_for('video.video') }}" alt="">
</div>
<form class="" method="post">
<div class="btn-group" style="width:100%">
<button style="width:33.3%">Apple</button>
<button style="width:33.3%">Samsung</button>
<button style="width:33.3%">Sony</button>
</div>
</form>
<div class="container new_container">
<div class="col-md-12 text-center">
<button onclick="switch_theme()" class="btn btn-light shadow-none" id="switch_button" style="width: 15%;">Dark Mode</button>
</div>
</div>
<script>
function switch_theme() {
const theme = document.getElementById('switch_theme').className;
if(theme === "dark-theme") {
document.getElementById('switch_theme').className = "light-theme";
document.getElementById('switch_button').className = "btn btn-dark shadow-none";
document.getElementById('switch_button').innerHTML = "Light Mode";
} else {
document.getElementById('switch_theme').className = "dark-theme";
document.getElementById('switch_button').className = "btn btn-light shadow-none";
document.getElementById('switch_button').innerHTML = "Dark Mode";
}
}
</script>
{% endblock %}
To conclude I say that I don't necessarily need a solution with python, but I would also be fine with a solution that include maybe a javascript function that runs the python function of my SerialHandler object.
Thanks in advance for the answers.
The code you provided doesn't help much. From what I understood you want to call your flask API endpoint (that will call the python function) repeatedly if someone keeps pressing a button inside a form element. This can be done in the front end with JavaScript itself. Something like -
<form method="POST">
<button id="formbutton">Click me!</button>
</form>
<script>
// grab the button
formBtn = document.querySelector('#formbutton')
let isMouseDown = false
// don't send the form automatically
formBtn.addEventListener('click', function(e) {
e.preventDefault()
})
// keep track of isMouseDown
formBtn.addEventListener('mousedown', function(e) {
isMouseDown = true
})
formBtn.addEventListener('mouseup', function(e) {
isMouseDown = false
})
// how many times to call the backend
setInterval(function() {
if(isMouseDown) {
// can also use axios & pass custom data
fetch('http://your.server/end/point', {
method: 'POST'
}).then(res => console.log(resres))
}
}, 200)
</script>
This may not be the best way to do it but will get the job done. If there are multiple buttons just add them in an array & add event listeners on them in a loop.

When data changes in my chatbot, page should get reloaded with new data

In web page (chatbot) in flask python, when data changes (new messages enter the new data), page should get reloaded with new data .Pip installs are done
Here I am using a Pretrained model of chatbot(DialoGPT-small) which will answers from the bot side.
from flask import Flask, render_template, request, jsonify
from datetime import datetime
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import time
app = Flask(__name__)
global chat_data
global tokenizer
global model
global chat_history_ids
chat_data=[
{'typer': 'User', 'message': 'Hello! I am your New friend', 'Time': '12:45'},
]
chat_history_ids = None
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
print('Model loaded')
#app.route("/",methods=['POST', 'GET'])
def chatpage():
global chat_data
global tokenizer
global model
global chat_history_ids
if 'messages' in request.form:
new_user_input_ids = tokenizer.encode(request.form['messages'] + tokenizer.eos_token, return_tensors='pt')
bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) if chat_history_ids!=None else new_user_input_ids
chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
bot_data = (tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True))
chat_data = chat_data + [{'typer': 'Man', 'message': request.form['messages'], 'Time': datetime.now().strftime("%H:%M")}]
chat_data = chat_data + [{'typer': 'User', 'message': bot_data, 'Time': datetime.now().strftime("%H:%M")}]
return render_template('Chat.htm',chat_data=chat_data)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
**My HTML CODE
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<title>ChatBot</title>
<script>
$(function(){
console.log("Went in first time")
$('#message_send').click(function(){
$.ajax({
data : {
'messages' : document.getElementById('message_input').value
},
type: 'POST',
url : "{{url_for('chatpage')}}",
success: function(response) {
console.log("Downloaded")
location.reload(true);
},
error: function(error) {
console.log(error)
},
});
});
});
</script>
<head>
</head>
<body>
<div class="window">
<div id="message_view" class="invisible-scrollbar ">
{% for chatted_data in chat_data%}
{% if chatted_data.typer == "Man" %}
<div class="right_box_container reloadPage();">
<div class="message_box right_message_box">
{{chatted_data.message}}
<div class="timestamp">{{chatted_data.Time}}</div>
</div>
</div>
{% else %}
<div class="gap">
</div>
<div class="left_box_container reloadPage();">
<div class="message_box left_message_box">
{{chatted_data.message}}
<div class="timestamp">12:38 PM</div>
</div>
</div>
{% endif %}
{% endfor %}
</div>
<form style="box-shadow: 0 5px 50px #b5b5b5;" >
<div id="message_container">
<textarea type="text" class="form-control invisible-scrollbar" placeholder="Type here..." id="message_input"></textarea>
</div>
<div id="message_send" class="ripple">
<button id="send_button">
<i class="fas fa-caret-right" id="send_button"></i>
</button>
</div>
</form>
</div>
</body>
</html>
The problem is that the page is not reloading with the new data, So I want a code to Reload the page, each time when new data gets added to chat_data(Dictionary)
{The page should reload after the bots message is added to the Chat_data}
Change your success to
document.getElementById("message_view").innerHTML => `<div class="right_box_container">
<div class="message_box right_message_box">
${document.getElementById('message_input').value}
<div class="timestamp">${new Date().toLocaleDateString()}</div>
</div>
</div>`
No need to reload

Adding items to Wishlist | Django

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()

How do you change an HTML tag with certain conditions?

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.

Odd behaviour in Django web app

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

Categories