I'm new to Django. I'm using Mezzanine 4.2.3 (Django 1.10.8 under the hood according to requirements.txt). I have a Postgres database of details about movies. I want to display 10 movies on a page.
I tried asking about this method but couldn't get a suitable solution, so now I'm trying to to write my own SQL query. But, I don't know how to create the context.
In the code below, I first randomly collect ten countries from a list of countries. Next, I iterate over the list and use each country to acquire a row in a Postgres database. Then, I make a dictionary from each row and become stuck at trying to make the context for the template.
import psycopg2
from psycopg2 import sql
from .countries import countries # Just a Python list of countries
import random
class MoviesListView(generic.ListView):
model = Movies
connection = psycopg2.connect([DB DETAILS])
c = connection.cursor()
def get_context_data(self, **kwargs):
random_countries = []
while len(random_countries) < 10:
choice = random.choice(countries)
if choice not in random_countries:
random_countries.append(choice.lower())
else:
pass
for country in random_countries:
get_rows = "SELECT * FROM movies WHERE LOWER(production_countries) LIKE %s LIMIT 1;"
c.execute(get_rows, ('%' + country + '%',))
rows = c.fetchall()
for i in rows:
row_dict = {}
row_dict['id'] = i[0]
row_dict['original_title'] = i[3]
row_dict['release_date'] = i[6]
row_dict['production_countries'] = i[8]
# Point at which I'm stuck.
# Context().push(row_dict)
# return Movies.objects.raw(get_rows, ('%' + country + '%',))
template_name = r"movies_crud/movies_list.html"
I read the Django documentation on Context()
and I thought either Context().push()
or Context.update()
would help create the context. But it's not working out.
I also tried .raw()
but it won't work because I'm trying to generate the context dynamically with a for
loop.
How do we make a Django context in this case?
Update: To give an idea of what I'm trying to do, the template looks like this:
{% for object in object_list %}
{{ object.title }}
{% endfor %}
It displays 10 movie titles.
PS: I worked on this problem for 16 hours straight and read what I could before asking this question. So, it's a minor thing but, it's not nice that someone drops a downvote without leaving a single word to explain it.