Flask mongoengine pagination - python

I have a small Flask app which renders blog posts:
views.py:
class ListView(MethodView):
def get(self, page=1):
posts = Post.objects.all()
return render_template('posts/list.html', posts=posts)
This is all good, but I would like to add pagination to the posts object. Looking at the project docs, I see there is a pagination class.
So I tried this:
class ListView(MethodView):
def get(self, page=1):
posts = Post.objects.paginate(page=page, per_page=10)
return render_template('posts/list.html', posts=posts)
But now I get an error:
TypeError: 'Pagination' object is not iterable
So how do I iterate through my posts in the template?

The Pagination object has an items list which will contain the mongoengine document objects (in your case the Post objects). This list can be iterated through to display the documents.
For example, in your template:
{% for post in posts.items %}
{{ post.title }}
{{ post.content }}
{% endfor %}
To get the actual page numbers for pagination links, use iter_pages():
<div id="pagination-links">
{% for page in posts.iter_pages() %}
{{ page }}
{% endfor %}
</div>
Both the documentation and the github link above, have a better example for pagination links:
{% macro render_pagination(pagination, endpoint) %}
<div class=pagination>
{%- for page in pagination.iter_pages() %}
{% if page %}
{% if page != pagination.page %}
{{ page }}
{% else %}
<strong>{{ page }}</strong>
{% endif %}
{% else %}
<span class=ellipsis>…</span>
{% endif %}
{%- endfor %}
</div>
{% endmacro %}

Related

Reverse for 'surveydetails' not found. 'surveydetails' is not a valid view function or pattern name

I've been stuck on this for a while, can't seem to fix the error. I've checked the code a hundred times but obviously there is something I'm missing. I have installed my app also.
Can anybody see what I'm missing?
views.py
def survey_details(request, id=None):
context = {}
surveys = Survey.objects.get(id=id)
context['survey'] = survey
return render(request, 'surveydetails.html', context)
feedback.urls.py
path('details/<int:id>', views.survey_details, name="surveydetails"),
surveys.html
{% extends 'main.html' %}
{% block content%}
<h1>Surveys</h1>
<h2>list of {{title}} </h2>
{% if surveys %}
<ul>
{% for survey in surveys %}
<li>
{{ survey.title }}
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no surveys.</p>
{% endif %}
{% endblock %}
surveydetails.html
{% extends 'main.html' %}
{% block content%}
<h1>Surveys</h1>
<h2>Detail page</h2>
<h3>{{question.title}}</h3>
<p>Details page of {{question.title}}</p>
{% endblock %}
Here you are not passing the survey id.
{% for survey in surveys %}
<li>
{{ survey.title }}
</li>
{% endfor %}

Frozen-Flask pagination links doesn't load the new page

I am trying to freeze my Flask blog app with Frozen Flask but the problem is I can't get the pagination to work correctly after the freeze().
I'm using the app factory pattern.
Here's my main.routes.py:
#bp.route('/home')
#bp.route('/index')
#bp.route('/')
def index(form=None, methods=['GET', 'POST']):
latest_posts = load_latest_posts(10)
with db_session(autocommit=False):
page = 1
posts = load_all_posts().paginate(page, 10, False)
next_url = url_for('main.index', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('main.index', page=posts.prev_num) \
if posts.has_prev else None
if current_user.is_anonymous:
return render_template('main/index.html', title='Home', posts = posts,
prev_url=prev_url, next_url=next_url, latest_posts=latest_posts)
load_all_posts() does what is says, returning Post.query.order_by(Post.pub_date.desc())
load_latest_posts(n) is basically the same but fetches the latest (n) posts.
As you see, I'm passing the pagination object to posts which I use in my main/index.html template to render the pagination items:
{% extends 'base.html' %}
{% block posts_preview %}
{% for post in posts.items %}
{% include 'posts/_post.html' %}
{% endfor %}
{% endblock posts_preview %}
{% block footer %}
<ul class="pagination">
{% if prev_url %}
<li>«</li>
{% endif %}
{% for page_num in posts.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=3) %}
{% if page_num %}
{% if posts.page == page_num %}
<li><a class="active" href="{{url_for('main.index', page=page_num) }}">{{ page_num }}</a></li>
{% else %}
<li>{{ page_num }}</li>
{% endif %}
{% else %}
...
{% endif %}
{% endfor %}
{% if next_url %}
<li>»</li>
{% endif %}
</ul>
{% endblock footer %}
_post.html is nothing fancy, just another template that includes post structure.
If I run this in Flask, it works without a problem. When generating static site with Frozen Flask, page numbers are there but clicking on them wouldn't redirect me anywhere. I see the URL being changed from http://127.0.0.1:5000/ to http://127.0.0.1:5000/?page=2 but the new content doesn't load, only refreshing the current page.
What might be the issue here ? How can I load pages and pagination correctly?
According to the Frozen Flask documentation on how the filenames are generated:
Query strings are removed from URLs to build filenames. For example,
/lorem/?page=ipsum is saved to lorem/index.html. URLs that are only
different by their query strings are considered the same, and they
should return the same response. Otherwise, the behavior is undefined.
This means that, unfortunately, http://127.0.0.1:5000/ and http://127.0.0.1:5000/?page=2 will refer to exactly the same page. To get pagination to work, you'd need to make sure that the page number was part of the URL before the query string - something like http://127.0.0.1:5000/page2/.

Trying to display a list of youtube videos into django template with django-embed-video

I am trying to embed a list of youtube videos, in which more videos will be added over time, into my django app using django-embed-video. Going after their documentation I did the following:
models.py
from embed_video.fields import EmbedVideoField
class Youtube(models.Model):
video = EmbedVideoField()
slug = models.SlugField(max_length=200, db_index=True, unique=True)
def __str__(self):
return self.video
admin.py
from .models import Youtube
from embed_video.admin import AdminVideoMixin
class YoutubeAdmin(AdminVideoMixin, admin.ModelAdmin):
list_display = ('video', 'slug')
admin.site.register(Youtube, YoutubeAdmin)
views.py
from .models import Youtube
def display_video(request):
videos = Youtube.objects.all()
context = {'videos': videos}
return render (request, 'scienceblog/post/videos.html', context)
videos.html
{% extends "base.html" %}
{% load embed_video_tags %}
{% video item.video 'small' %}
{% block content %}
{% if videos %}
{% for v in videos %}
{{ v }}
{% endfor %}
{% else %}
<p>No videos yet</p>
{% endif %}
{% endblock %}
Everything works perfect in the admin site. The youtube links are added and the videos are displayed. However I am very unsure about the HTML tags. The browser only displays the youtube links as a string when videos.html is rendered. How can I display the videos?
Thanks for the quick answer raratiru! It brought me on the idea to look into the code of the django-embed-video app itself. I fiddled around with it a bit and now it works just how I wanted it to work. The relevant code is:
videos.html
{% load embed_video_tags %}
{% for v in videos %}
{% video v.video as my %}
<iframe width="{{ 480 }}" height="{{ 320 }}" src="{{ my.url }}"
frameborder="0" allowfullscreen></iframe>
{% endvideo %}
{% endfor %}
You need to acquire the EmbedVideoField() which is video according to models.py. Therefore, the loop should read something like:
{% extends "base.html" %}
{% load embed_video_tags %}
{% video item.video 'small' %}
{% block content %}
{% if videos %}
{% for v in videos %}
{{ v.video }}
{% endfor %}
{% else %}
<p>No videos yet</p>
{% endif %}
{% endblock %}
It is possible that the EmbedVideoField() has more attributes that have to be accessed, you have to check the relevant docs. For example, if the embed code is stored in EmbedVideoField().embed_code you can reach it as such:
{% for v in videos %}
{{ v.video.embed_code }}
{% endfor %}

How to determine wagtail Page content type within django template?

The core problem is that handling of wagtail RichTextField and StreamField is radically different in the templates.
I'm trying to accomplish something similar to the following:
{% with post=post.specific %}
{% if post.content_type == 'streamfield' %}
{% include_block post.body %}
{% else %}
{{ post.body|richtext }}
{% endif %}
{% endwith %}

Django Get Primary + Foreign Attributes

I have two models: Site and Metric.
I want to display the Metric values alongside each Site.
My views.py is as follows:
from django.shortcuts import render
from .models import Site, Metric
def site_graph(request):
sites = Site.objects.order_by('name')
metrics = [s.metric_set.all() for s in sites]
return render(request, 'da/site_graph.html', {'sites': sites, 'metrics': metrics})
And my template content looks like this:
{% block content %}
{% for metric in metrics %}
[
{% for query in metric %}
{{ query.domain_authority }}
{{ query.date_queried }}
{% endfor %}
]
{% endfor %}
{% endblock content %}
I am not sure how I would go about getting the data I need in Django.
This data is going to be eventually passed onto d3.js for visualization which is why I need the data from the matching the primary key for each Site to be together.
You can use a list of dictionaries:
def site_graph(request):
metrics=[]
sites = Site.objects.order_by('name')
for site in sites:
metrics_site={}
metrics_site["site"] = site
metrics_site["metrics"] = site.metric_set.all()
metrics.append(metrics_site)
return render(request, 'da/site_graph.html', {'metrics': metrics})
And then in the template:
{% block content %}
{% for metric in metrics %}
{{ metric.site.name }}
{% for query in metric.metrics %}
{{ query.domain_authority }}
{{ query.date_queried }}
{% endfor %}
{% endfor %}
{% endblock content %}
metric.site.name is just an example if your model "site" contains a field "name" that you want to show.

Categories