I am getting data from the server. The view must renders an html page without reloading the entire page، but this renders whole page including the header of current page, this is a problem, each time request to the server to get the data
Here is the HTML that the server send with fetch when i click on button
{% for post in posts %}
<div class="posts-item">
{{post.description|linebreaks|truncatewords:20}}
Published at {{post.created}} by {{post.author}}
<br>
{% for tag in post.tag.all %}
<a href="{% url 'social:post_list_by_tag' tag.slug %}">{{tag.name}}</a>
{% if forloop.last %}, {% endif %}
{% endfor %}
<a href="{% url 'social:post_detail' post.pk %}">post details</a>
<hr><br>
</div>
{% endfor %}
Here is the current page, posts-list.html:
{% extends 'parent/base.html' %}
{% block title%} posts list {% endblock %}
{% block content %}
<div class="posts">
{% for post in posts %}
{{post.description|linebreaks|truncatewords:20}}
Published at {{post.created}} by {{post.author}}
<br>
{% for tag in post.tag.all %}
<a href="{% url 'social:post_list_by_tag' tag.slug %}">{{tag.name}}</a>
{% if forloop.last %}, {% endif %}
{% endfor %}
<a href="{% url 'social:post_detail' post.pk %}">post details</a>
<hr><br>
{% endfor %}
</div>
<button class="load-more">load more</button>
<script>
var page = 2;
function loadMore(){
var url = '{% if tag_slug %}{% url "post_list_by_tag" tag.slug %}{% else %}{% url "social:post_list" %}{% endif %}'+'?page='+page;
fetch(url, {
method: 'GET',
headers: {
'content-type': 'text/html', 'x-requested-with': 'XMLHttpRequest'
},
}).then(function(response){
return response.text();
}).then(function(html){
document.querySelector(".post").insertAdjacentHTML("beforeend",html);
page++;
})
}
var btnLoadMore = document.querySelector(".load-more");
btnLoadMore.addEventListener("click", loadMore);
</script>
{% endblock %}
views.py
def post_list(request, tag_slug=None):
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
posts = Post.objects.filter(tags__in=[tag])
else:
posts = Post.objects.all()
tag = None
page = request.GET.get('page')
paginator = Paginator(posts, 1)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = []
if request.headers.get("x-request-with") == "XMLHttRequest":
return render(request, "social/fetch-post.html", {"posts": posts})
context = {'posts': posts, 'tag': tag}
return render(request, "social/posts-list.html", context)