load more feature or endless pagination - javascript

I recently learnt I need pagination otherwise page won't load faster.
so I implemented it.
But now that I finished implemented, I realize I have some problem.
My web has a format like this
The above is the top part of the page
and the above is the below part of the page.
all my posts are going into the below part, and because more posts I write more posts will be there I implemented pagination.
the pagination works fine, but when I go to the next page the top part remains there while the below part shows new posts. (I have implemented this without realizing the existence of the top part)
I don't want my users to see the top part every time they click next page.
I think I have two ways to solve this problem.
One is to somehow not show the top part when they click next page.
Or
I use load more button to show more posts instead of going into another page.
Problem is I don't know how to do either one of them..can some one please help me?
def category_detail(request, slug):
obj = NewsCategory.objects.get(slug=slug)
newsInCat = obj.news_set.all() #for the list of news
paginator = Paginator(newsInCat, 25) # Show 25 contacts per page
page = request.GET.get('page')
try:
news_set = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
news_set = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
news_set = paginator.page(paginator.num_pages)
bestInCat = obj.news_set.get_bestInCat()
context = {
"obj":obj,
"news_set":news_set,
"newsInCat":newsInCat,
"bestInCat":bestInCat,
}
return render(request, "news/category_detail.html", context)
<div class="row">
<div>
{% for news in news_set %}
<div class='col-sm-4'>
<div class="content">
<figure class="story-image">
</figure>
<div id="forever "style="margin-bottom:30px;">
<a href='{{news.get_absolute_url }}' style="text-decoration:none; color:#282E5C;"><h4 style="font-size: 18px;
font-weight: 400;">{{news.title}}</h4></a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
<div class="pagination">
<span class="step-links">
<!-- {% if news_set.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ news_set.number }} of {{ news_set.paginator.num_pages }}.
</span> -->
{% if news_set.has_next %}
Load More
{% endif %}
</span>
</div>

1) in the html you can show top block if page number equals 1. For example
{% if news_set.number==1%}
{{ top_block}}
{% endif %}
<div class="row">
<div>
{% for news in news_set %}
<div class='col-sm-4'> ....
2) you can render partial html if request is ajax
Here is simple code
views.py
def category_detail(request, slug):
obj = NewsCategory.objects.get(slug=slug)
newsInCat = obj.news_set.all() #for the list of news
paginator = Paginator(newsInCat, 25) # Show 25 contacts per page
page = request.GET.get('page')
try:
news_set = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
news_set = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
news_set = paginator.page(paginator.num_pages)
if request.is_ajax():
context = {
'news_set':news_set
}
return render(request,"news/category_detail_ajax.html",context)
else:
bestInCat = obj.news_set.get_bestInCat()
context = {
"obj":obj,
"news_set":news_set,
"newsInCat":newsInCat,
"bestInCat":bestInCat,
}
return render(request, "news/category_detail.html", context)
category_detail_ajax.html
{% for news in news_set %}
<div class='col-sm-4'>
<div class="content">
<figure class="story-image">
</figure>
<div id="forever "style="margin-bottom:30px;">
<a href='{{news.get_absolute_url }}' style="text-decoration:none; color:#282E5C;"><h4 style="font-size: 18px;
font-weight: 400;">{{news.title}}</h4></a>
</div>
</div>
</div>
{% endfor %}
javascript
jQuery(document).on('click','.load-more',function(e){
e.preventDefault();
jQuery.ajax({
url:jQuery(this).attr('href')
}).done(function(data){
jQuery('.row>div').append(data);
});
});

Related

How can I re-run a Django For Loop inside a HTML Div using Javascript on Click Event

I have a HTML div like this,
<div class="coment-area ">
<ul class="we-comet">
{% for j in comment %}
<div id="delete_comment{{j.id}}" class="mt-3">
{% if j.post_id.id == i.id %}
<li >
<div class="comet-avatar">
{% if j.user_id.User_Image %}
<img class="card-img-top" style=" vertical-align: middle;width: 50px;height: 50px;border-radius: 50%;" src= {{ j.user_id.User_Image.url }} alt="">
{% else %}
<img class="card-img-top" style=" vertical-align: middle;width: 60px;height: 60px;border-radius: 50%;" src="static\images\resources\no-profile.jpg">
{% endif %}
</div>
Inside of it is a For Loop that is executed when the page is first loaded.
Below this For Loop is a Comments Button
<div >
<button type="submit" onclick="comment_save(event,{{i.id}})" class= "my-2 ml-2 px-2 py-1 btn-info active hover:bg-gray-400 rounded ">Comment</button>
</div>
</div>
</li>
</ul>
</div>
Whenever this button of Comments is clicked, a function in Javascript is called which is defined below,
function comment_save(event,post_id)
{
var comment_value=$("#comment_value"+post_id).val();
var user_id=$("#comment_user_id"+post_id).val()
postdata={
"comment_value":comment_value,
"user_id":user_id,
"post_id":post_id
}
SendDataToServer("readmore",postdata,function()
{
alert()
})
$("#comment_value"+post_id).val(" ")
<! --- document.location.reload().. Something here that refresh that for loop --->
}
What I want is this that whenever the button is clicked, it re-executes that for Loop inside my main div without having to refresh the page. I have been trying to do this for two days but could not find any solution to this. Can anyone help me in doing this?
The Django Templating Language is executed server-side. That means the client (browser, running Javascript) has no access to it whatsoever.
Some of your options are:
Do everything back-end: Re-render the template (which you said don't want to do).
Do everything front-end: You could have your view function return the data used in your template loop and re-implement it in your front-end (but that makes the original template loop kind of pointless).
Hybrid: Return the data for only the new comment in your response and add it to the list with Javascript.

(JS) Markdown issue in flask

I have a small problem with markdown in my flash project.
I want markdown to work for all posts, currently it only works for the first post. I suspect I need to use some kind of loop, but I don't know what to do to make it work.
Code:
{% extends "layout.html" %}
{% block content %}
<article class="media content-section">
<div class="media-body">
{% for post in document.posts %}
<div class="article-metadata">
<h3><a class="article-title" href="{{ url_for('posts.post', post_id=post.id) }}">{{ post.title }}</a></h3>
<p class="article-content">{{ post.content }}</p>
</div>
{% endfor %}
</div>
</article>
<script>
const content_text = document.querySelector(".article-content");
content_text.innerHTML = marked(content_text.innerHTML);
</script>
{% endblock content %}
Pic of the posts on website
querySelector returns the first element with the class. You need to use querySelectorAll to get all the elements and then use for loop to loop and apply markdown to each element.
const content_text = document.querySelectorAll(".article-content");
for (i = 0; i < content_text.length; i++){
content_text[i].innerHTML = marked(content_text[i].innerHTML);
}

Show and hide text of different posts

I have several posts each of them composed of three parts : a title, a username/date and a body. What I want to do is to show the body when I click on either the title or the username/date and hide it if I click on it again. What I've done so far works but not as expected because when I have two or more posts, it only shows the body of the last post even if I click on another post than the last one. So my goal is only to show the hidden text body corresponding to the post I'm clicking on. Here is my code:
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}Test page{% endblock %}</h1>
<a class="action" href="{{ url_for('main_page.create') }}">New</a>
{% endblock %}
{% block content %}
{% for post in posts %}
<article class="post">
<header>
<script language="JavaScript">
function showhide(newpost)
{var div = document.getElementById(newpost);
if (div.style.display !== "block")
{div.style.display = "block";}
else {div.style.display = "none";}}
</script>
<div onclick="showhide('newpost')">
<h1>{{ post['title'] }}</h1>
<div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%d-%m-%Y') }}</div>
</div>
</header>
<div id="newpost">
<p class="body">{{ post['body'] }}</p>
</div>
</article>
{% if not loop.last %}
<hr>
{% endif %}
{% endfor %}
{% endblock %}
Of course I looked for a solution as much as I could but I'm kind of stuck plus I'm a complete beginner in HTML/JS/CSS. And one last thing, I'm currently using Python's framework Flask. Thank you by advance.
You need to give each of your posts a unique id for your approach to work.
Change your code to
<div id="{{post_id}}">
<p class="body">{{ post['body'] }}</p
</div>
where post_id is that post's unique id e.g. its id in the database you are using that you pass to the template in your view. Then, change the call to the onclick event handler to
<div onclick="showhide('{{post_id}}')">
If you don't have a unique id you can also use the for loop's index: replace all post_id instances above with loop.index. See Jinja's for loop docs for more information.

How to close Bootstrap modal window after set interval of time using Jquery?

I have a script which makes AJAX calls to update a page every 5 seconds. I want to display a alert/popup every time a change is observed i.e. for the first time when the page loads, I want to display a popup that says "Everything setup!" and on the subsequent page loads via AJAX, I'll display a popup IF there is any change. The popup stays on the page for 2 seconds and then disappears.
I am able to make the AJAX calls successfully. However, the popup window does not work as expected.
Observed behavior :- The popup window shows up on page load as expected, but it does not close after 2 seconds. However, the page refreshes after 5 seconds due to AJAX call. The popup remains in its place unless I manually close it.
I think I have figured out where the problem may be arising. The AJAX calls are being made through the setInterval() function of JS. I had removed that statement and tried calling the popup function and it worked as expected i.e. the page loaded and then the popup appeared. After 2 seconds the popup closed automatically. This method however is not helpful as I will not be able to perform the page reloads in the background after every 5 seconds.
The issue seems to arise from the AJAX calls.
HTML - dashboard.html
{% extends "base.html" %}
{% block content %}
<div id='modal-disp' class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
No new images!
</div>
</div>
</div>
<div class="image-area">
<div class="container dash-container main-body" >
<hr>
<div class="row">
<br>
<hr >
<br>
<div class="col-md-12">
<div class="jumbotron ">
<h1 id="hdr">DASHBOARD</h1>
</div>
</div>
</div>
{% if folders %}
<div class="row">
<div class="col-md-12 folder-list" id="info">
Please select the Date to view their corresponding test results.<br><br>
{% set ns = namespace(counter=0) %}
<table class="table table-hover ">
{% for row in range(rows) %}
<tr class="row-hover">
{% for data in range(3) %}
{% if ns.counter < folders|length %}
<td>
<a class="folder-link" href="{{ url_for('image',im=folders[ns.counter]) }}">{{ folders[ns.counter] }}</a>
<br>
{% set ns.counter = ns.counter + 1 %}
</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
</div>
{% endif %}
{% if images %}
<div class="row" id="info">
<span class="glyphicon glyphicon-backward" aria-hidden="true"></span>
</div>
<br><br>
<div class="row">
<div class="col-md-12" id="info">
{% set ns = namespace(counter=0) %}
<table class="table table-hover table-condensed table-bordered images-table" cellspacing="5" cellpadding="5">
{% for row in range(rows) %}
<tr class="image-hover">
{% for data in range(3) %}
{% if ns.counter < images|length %}
<td style="width:10%;">
<img src="{{ url_for('static',filename=images[ns.counter]) }}" alt="User Image" width="200" height="180">
<br>
{% set ns.counter = ns.counter + 1 %}
</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
</div>
{% endif %}
</div>
</div>
{% endblock %}
Javascript file -
<script type="text/javascript">
var first_time = 0;
var current_count = 0;
var total_count = 0;
function update(){
$('#modal-disp').modal('show');
setTimeout(function() { $("#modal-disp").modal('hide'); }, 2000);
if (first_time === 0){
current_count = $('td').length;
total_count = current_count;
first_time = 1;
//var txt = $("<p class='notify'></p>").text("No new images");
$('body').append("<div class='row'><div class='col-md-12'><p class='notify'><br>Up to date !</p></div></div>");
$('.notify').css({'color':'#06661f','font-size':'30px','font-family': "'Saira',sans-serif",'font-style':'bold','text-align': 'center'});
$('html, body').animate({scrollTop:$(document).height()}, 'slow');
//$('#myModal').modal('hide');
setTimeout(function() { $(".notify").text(""); }, 5000);
}
else {
total_count = $('td').length;
if (total_count>current_count){
$('.notify').text(total_count-current_count + " new image added !");
$('.notify').css({'color':'#bc0041','font-size':'30px','font-family': "'Saira',sans-serif",'font-style':'bold','text-align': 'center' });
$('html, body').animate({scrollTop:$(document).height()}, 'slow');
//alert(total_count-current_count + ' images added !');
current_count = total_count;
setTimeout(function() { $(".notify").text(""); }, 5000);
}
}
}
//setInterval(function(){ $('.image-area').load("{{ url_for('image',im=image_date) }}"); update(); }, 2000);
setInterval(function(){$('.image-area').load("{{ url_for('image',im=image_date) }}", function() {update();}); }, 5000);
</script>
Here, Flask is used in the back end. So I am calling the /image route every 5 seconds. For the sake of keeping the code simple, I am just displaying a static popup for now. The popup is defined at the top of the HTML file. My best guess is the AJAX calls are interfering with the DOM and as a result the modal ID tag is getting masked.
Please help.
EDIT 1:
Notice in Image 1, there is the popup and also the message - "Up to date!" at the extreme bottom of the page. This works as it should because the page is loaded for the first time.
Here, in image 2 you can see that the message -"Up to date" is not there anymore. This behavior is also expected because according to code logic, the message is displayed on initial page load only. It will not be displayed on subsequent AJAX page reloads. Check the function update() for clarity.
At the same time, you can see that the alert box has remained in its place. More than 10 seconds have passed and the alert box has not closed at all.
EDIT 2:
I have noticed that if I place the HTML for the modal inside the div tag with class="image-area", the popup closes after 2 seconds but its backdrop (i.e the grayed out background ) does not disappear. Also, because of this, the entire website becomes unresponsive. Clicking anywhere, on the screen has no effect and everything appears grayed out due to the presence of the backdrop.
The div with class area="image-area" defined at the top encloses all the HTML that is refreshed every 5 seconds. This part of the HTML is fetched from the back end.
Python - routes.py
#app.route('/image/<im>')
#login_required
def image(im):
image_src=[im+'/'+i for i in os.listdir(os.path.join(app.static_folder,im))]
rows=math.ceil(len(image_src)/3)
print(image_src)
return render_template('dashboard.html',title='Welcome',images=image_src,rows=rows,image_date=im)
The above behavior is observed when I move the modal HTML inside the topmost div tag as follows:
{% extends "base.html" %}
{% block content %}
<div class="image-area">
<div id='modal-disp' class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
No new images!
</div>
</div>
</div>
<div class="container dash-container main-body" >
<hr>
The following image shows the web page after the popup disappears. Note, clicking anywhere in the web page does not yield any response.

Django template showing \u200e code

Hey guys I am beyond frustrated/exhausted trying to fix this unicode code \u200e showing in my web page. I tried everything I can think of. Here is what my page looks like, its data scraped articles from news.google.com and shown on my page with the time submission (the time submission is where the \u200e pops up everywhere)
http://i.imgur.com/lrqmvWG.jpg
I am going to provide my views.py, my articles.html (the page in the picture that is set up to display everything), and header.html (for whatever reason. But this is the parent template of articles.html for the CSS inheriting). Also, I researched and know that the \u200e is a left-to-right mark and when I inspect the source in news.google.com, it pops up in the time submission element as
‎
like so:
<span class="al-attribution-timestamp">‎‎51 minutes ago‎‎</span>
I tried editing the views.py to encode it using .encode(encoding='ascii','ignore') or utf-8 or iso-8859-8 and a couple other lines of code I found researching deep on google but it still displays \u200e everywhere. I put it in so many different parts of my views.py too even right after the for loop (and right before + after it gets stored as data in the variable "b" and its just not going away. What do I need to do?
Views.py
def articles(request):
""" Grabs the most recent articles from the main news page """
import bs4, requests
list = []
list2 = []
url = 'https://news.google.com/'
r = requests.get(url)
sta = "‎"
try:
r.raise_for_status() == True
except ValueError:
print('Something went wrong.')
soup = bs4.BeautifulSoup(r.text, 'html.parser')
for listarticles in soup.find_all('h2', 'esc-lead-article-title'):
a = listarticles.text
list.append(a)
for articles_times in soup.find_all('span','al-attribution-timestamp'):
b = articles_times.text
list2.append(b)
list = zip(list,list2)
context = {'list':list, 'list2':list2}
return render(request, 'newz/articles.html', context)
articles.html
{% extends "newz/header.html" %}
{% block content %}
<script>
.firstfont (
font-family: serif;
}
</script>
<div class ="row">
<h3 class="btn-primary">These articles are scraped from <strong>news.google.com</strong></h3><br>
<ul class="list-group">
{% for thefinallist in list %}
<div class="col-md-15">
<li class="list-group-item">{{ thefinallist }}
</li>
</div>
{% endfor %}
</div></ul>
{{ list }}
{% endblock %}
header.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sacred Page</title>
<meta charset="utf-8" />
{% load staticfiles %}
<meta name="viewport" content = "width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'newz/css/bootstrap.min.css' %}" type = "text/css"/>
<style type="text/css">
html,
body {
height:100%
}
</style>
</head>
<body class="body" style="background-color:#EEEDFA">
<div class="container-fluid" style="min-height:95%; ">
<div class="row">
<div class="col-sm-2">
<br>
<center>
<img src="{% static 'newz/img/profile.jpg' %}" class="responsive-img" style='max-height:100px;' alt="face">
</center>
</div>
<div class="col-sm-10">
<br>
<center>
<h3><font color="007385">The sacred database</font></h3>
</center>
</div>
</div><hr>
<div class="row">
<div class="col-sm-2">
<br>
<br>
<!-- Great, til you resize. -->
<!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#E77200">-->
<div class="well bs-sidebar" id="sidebar" style="background-color:#E1DCF5">
<ul class="nav nav-pills nav-stacked">
<li><a href='/'>Home</a></li>
<li><a href='/newz/'>News database</a></li>
<li><a href='/blog/'>Blog</a></li>
<li><a href='/contact/'>Contact</a></li>
</ul>
</div> <!--well bs-sidebar affix-->
</div> <!--col-sm-2-->
<div class="col-sm-10">
<div class='container-fluid'>
<br><br>
<font color="#2E2C2B">
{% block content %}
{% endblock %}
{% block fool %}
{% endblock fool %}
</font>
</div>
</div>
</div>
</div>
<footer>
<div class="container-fluid" style='margin-left:15px'>
<p>Contact | LinkedIn | Twitter | Google+</p>
</div>
</footer>
</body>
</html>
If you want, you can use replace() to strip the character from your string.
b = articles_times.text.replace('\u200E', '')
The reason that you see \u200E in the rendered html instead of ‎ is that you are including the tuple {{ thefinallist }} in your template. That means Python calls repr() on the tuple, and you see \u200E. It also means you see the parentheses, for example ('headline' '\u200e1 hour ago')
If you display the elements of the tuple separately, then you will get ‎ in the template instead. For example, you could do:
{% for headline, timeago in list %}
<div class="col-md-15">
<li class="list-group-item">{{ headline }} {{ timeago }}
</li>
</div>
{% endfor %}

Categories

Resources