Flask app not rendering data from database (psql) - python

{% extends "layout.html" %}
{% block heading %}
Search Results
{% endblock %}
{% block body %}
fgrgrgtgtg
<ul>
{% for book in books %}
<li>
{{ books.title }}
</li>
{% endfor %}
</ul>
{% endblock %}
#app.route("/search", methods=["GET", "POST"])
def search():
# Query database for book title
books = db.execute("SELECT * FROM books WHERE title = :title",
{"title": request.form.get("title")}).fetchall()
print (books)
return render_template("search.html", books=books)
I'm working on a project for CS50W and I'm stuck. I'm trying to implement a very bare-bones search function that should find all books in my database by title, and then render them on search.html. I just want to get it to work in the simplest way possible before I start adding more complexities to it.
I added "print(books)" in my python code just to make sure that I was successfully pulling the data from the database, and it appears that that is working properly, as it prints the expected results in my terminal. But nothing appears in my html on search.html.

You have a typo; the variable within your loop is book, not books.
{% for book in books %}
<li>
{{ book.title }} # here
</li>
{% endfor %}

Related

How to display the list of followers of a user in Flask

I am new to Flask, I have a created a social media blog using Flask and I have used flask-SQLAlchemy database. I have incorporated the follow feature in blog, now I want to display the list of followers of a user and I have been getting an error and the results are not getting displayed.
Here is the code:
the route to display followers
#app.route("/userListFollowers/<username>")
#login_required
def listFollowers(username):
user = User.query.filter_by(username=username).first_or_404()
folruser = user.followers.all()
return render_template('userListFollowers.html', users=folruser)
the userListFollowers.html file that displays the list of followers
{%extends "layout.html" %}
{% block body %}
<div class="jumbotron">
<h2 style="text-align: center;">Followers</h2>
{% for users in listFollowers%}
{{username.username}}
{% endfor %}
</div>
{% endblock %}
I can't really understand how to get this working.
This is the error
You should be using render_template to render HTML templates, you are returning a redirect to the same view function so you keep endlessly redirecting.
Also you need to pass your list of followers into the render_template function so that it will render them with your Jinja code
For your jinja code:
{%extends "layout.html" %}
{% block body %}
<div class="jumbotron">
<h2 style="text-align: center;">Followers</h2>
<ul>
{% for users in listFollowers%}
<li>{{users.username}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}

How to display the result from SQLite db to html?

I am currently learning to build a small web-app. I want to show the list of employees in the web page, and later the ability to add a new employee data to the database. I am using SQlite db and Python Flask.
But I am stuck at this error message: UnboundLocalError: local variable 'rows' referenced before assignment. So my question is, how do I fetch the content of my SQlite db and show them on my webpage? I'd like to show it as a table as well.
Here's my HTML code:
{% extends "layout.html" %}
{% block body %}
<h1> Employees </h1>
<ul>
{% for employee in employees %}
<li> {{ employee }}</li>
{% endfor %}
</ul>
Add a new employee
{% endblock %}
And my python code:
#app.route("/")
def tasks():
rows = db.execute("SELECT * FROM employees")
return render_template("employee_list.html", rows= rows)
Anybody can help me? Thank you.
use macro
{% macro render_comment(emp) %}
<li>{{ emp }}</li>
{% endmacro %}
<ul>
{% for emp in employees %}
{{ render_comment(emp) }}
{% endfor %}
</ul>
and change
return render_template("employee_list.html", rows= rows)
to
return render_template("employee_list.html", employees= rows)

Django - The page don't load after click

i'm new in Django developing.
I'm following the tutorial about Library on MDN (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django)
Until i follow the code all work but i'm trying implement author page by myself. Probably is very stupid issue but is one day that i'm turning around like a dog with its tail.
There is 2 page: author_list and author detail.
I set urls.py (in my project) i set view.py and crate my template.
I follow the same step of tutorial for realize book_list and book_detail but when i click on my author the page don't go to the detail of that author and stay in author_list.html.
Here the code urls.py :
path('authors/', views.AuthorListView.as_view(), name='authors'),
path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'),
Here views.py:
class AuthorListView(generic.ListView):
model = Author
class AuthorDetailView(generic.ListView):
model = Author
Here author_list.html with link get_absolute_url:
{% extends "base_generic.html"%}
{% block content %}
<h1>Author list</h1>
{% if author_list %}
<ul>
{% for aut in author_list %}
<li>{{ aut.first_name }} - {{ aut.last_name }}</li>
{% endfor %}
</ul>
{% else %}
<p>There are no author.</p>
{% endif %}
{% endblock %}
Here author_detail.html:
{% extends "base_generic.html" %}
{% block content %}
<h1>Author</h1>
{% if author %}
<p><strong>Nome: </strong> {{ author }}</p>
<p><strong>Nato il : </strong> {{ author.date_of_birth }}</p>
<p><strong>Morto il : </strong> {{ author.date_of_death }}</p>
{% endif %}
{% endblock %}
Here the screenshot
Author_list.html before click url=catalog/authors/
After click url change but page not
Thank to all for help
I believe you need DetailView instead of ListView for AuthorDetailView.
Looks like a typo to me, you want generic.DetailView (instead of ListView) for the author/<int:pk> path.
I also don't think it's right to extend base_generic for the template for the detail view. But that depends exactly what is in this base template.

How To Access Many to Many Attribute in Django

I am very new to web development and I have created a sample project using Django. So far I have a Django powered page that displays the contents of one of my database's model objects which is called Publications. The code I have in my view template is:
<html><head><title>Publications</title></head>
<body>
<h1>Publications</h1>
<ul>
{% for publication in publication_list %}
<li>{{ publication.title }} </li>
{% endfor %}
</ul>
</body></html>
This works fine, but now I would like to access and display a many to many attribute on Publications called Tags. I have tried adding another for tag as follows:
<html><head><title>Publications</title></head>
<body>
<h1>Publications</h1>
<ul>
{% for publication in publication_list %}
<li>{{ publication.title }} </li>
{% for tag in publication_list.tags %}
<li>{{ tag.title }} </li>
{% endfor %}
{% endfor %}
</ul>
</body></html>
I realize this is quite wrong, but I don't see how to access the Tags model. For reference, my function for displaying the publications in the view is:
def display_publications(request):
publication_list = Publication.objects.order_by('title')[:10]
return render(request, 'publications.html', {'publication_list': publication_list})
And my Publications and Tag Models are:
class Tag(models.Model):
title = models.CharField(max_length=50)
class Publication(models.Model):
title = models.CharField(max_length=200)
tags = models.ManyToManyField(Tag, blank=True)
Any help is appreciated.
What you are doing only accesses the ManyRelatedManager. You need to specify a query against that manager. In python, it would be:
publication.tags.all()
In a django template it would be:
{% for tag in publication.tags.all %}
{{ tag }}
{% endfor %}
This should be covered in the official documention on many-to-many relationships.
Edit: Here's a good example of how many-to-many relationships work: https://docs.djangoproject.com/en/1.5/topics/db/examples/many_to_many/
Because you seem to be having some trouble with this, given your comments on the other question, here are the changes to the template. You do not need to modify the view at all from what you have given above.
{% for publication in publication_list %}
<li>{{ publication.title }}
<ul>
{% for tag in publication.tags.all %}
<li>{{ tag.title }} </li>
{% endfor %}
</li>
</ul>
{% endfor %}

Displaying Page Numbers with django-tables2

I'm currently displaying a dataset using django-tables2.
The docs make no mention of this in particular, so I'm guessing this'll take probably some table overriding - but, I'm hopeful someone out there has already accomplished this.
How can I render page numbers using django-tables2 below my table? What I'd like to be able to display is a horizontal list of page numbers that the user can click.
Thanks in advance.
you need to create a custom page rendering template - you don't need to override any classses.
To do that, start by copying the file
PYTHON\Lib\site-packages\django_tables2\templates\django_tables2\table.html
to the templates directory inside your django application and rename it to mytable.html or whatever else you like.
Now, you need to change the pagination block of that file. There are many ways to do what you like, but a simple way is to add the following lines inside the pagination block (you may remove or keep the other things that are there depending on your specific needs):
{% block pagination.allpages %}
{% for p in table.paginator.page_range %}
{{ p }}
{% endfor %}
{% endblock pagination.allpages %}
Finally, to use your template, just pass your custom template name to the render_table command:
{% load render_table from django_tables2 %}
...
{% render_table table "mytable.html" %}
This is very simple and will give you trouble if you have many pages (so you have to use some ifs to check the number of pages through the table.paginator.num_pages variable). Also, you may highlight the current page and disable the link by using the table.page.number variable.
The above are left as an excersise to the reader :)
Improving on #Serafeim answer (or solving the exercise he left): Here is a pagination block which, using only Django template syntax, renders page numbers that:
are enclosed in a <ul> HTML block, whith CSS classes that "play well" with Bootstrap;
if there are more than 8 pages, at most 3 pages below and above current page are shown;
first and last pages are always shown, with ellipsis between them and the start or end of the range (if needed).
{% with current_page=table.page.number page_count=table.paginator.num_pages rows_per_page=table.page.object_list|length total_rows=table.page.paginator.count %}
{% block pagination %}
<ul class="pagination">
{% block pagination.allpages %}
<li class="current">
{% blocktrans %}Page {% endblocktrans %}
</li>
{% for page in table.paginator.page_range %}
{% with range_start=current_page|add:"-3" range_end=current_page|add:"3" page_count_minus_5=page_count|add:"-5" page_count_minus_1=page_count|add:"-1" %}
{% if page == current_page %}
<li class="active">
<span>{{ page }}</span>
</li>
{% elif page == 1 or page >= range_start and page <= range_end or page == page_count %}
<li class="next">
{{ page }}
</li>
{% endif %}
{% if page == 1 and current_page > 5 or page == page_count_minus_1 and current_page <= page_count_minus_5 %}
<li class="current">...</li>
{% endif %}
{% endwith %}
{% endfor %}
{% endblock pagination.allpages %}
{% block pagination.cardinality %}
<li class="cardinality">
{% if total_rows != rows_per_page %}{% blocktrans %}
{{ rows_per_page }} of {{ total_rows }}{% endblocktrans %}
{% else %}
{{ total_rows }}
{% endif %}
{% if total_rows == 1 %}
{{ table.data.verbose_name }}
{% else %}
{{ table.data.verbose_name_plural }}
{% endif %}
</li>
{% endblock pagination.cardinality %}
</ul>
{% endblock pagination %}
{% endwith %}
Pagination is introduced in version# >= 2.0.0
https://django-tables2.readthedocs.io/en/latest/pages/CHANGELOG.html
Simply add following code in settings.py. Pagination with number will be rendered with bootstap 4 style. Make sure you have bootstrap 4 reference in html template.
DJANGO_TABLES2_TEMPLATE = 'django_tables2/bootstrap4.html'
And check out more styles in documentation.
https://django-tables2.readthedocs.io/en/latest/pages/custom-rendering.html#available-templates

Categories

Resources