Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show modal from another html after a successful form submission?
Here is the code I'm currently using. I've been trying to figure out how to solve this but I think I can't since it been hours. Any suggestions and answer will be appreciated. urls.py from django.urls import path from .views import pos, save_pos, receipt app_name = 'pos' urlpatterns = [ path('point-of-sale/', pos, name='point-of-sale'), path('save-pos/', save_pos, name='save-pos'), path('receipt/<int:transaction_id>/', receipt, name='receipt-modal'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from shop.models import Items from .models import Transaction, TransactionItems from .forms import TransactionForm from datetime import datetime from django.http import HttpResponse, JsonResponse import json def pos(request): products = Items.objects.filter(is_sold=False) product_json = [{'id':product.pk, 'name':product.name, 'price':float(product.price)} for product in products] context = { 'products' : products, 'product_json' : json.dumps(product_json) } return render(request, 'pos.html', context) def save_pos(request): pref = datetime.now().year + datetime.now().year i = 1 while True: code = '{:0>5}'.format(i) i += int(1) check = Transaction.objects.filter(code = str(pref) + str(code)).all() if len(check) <= 0: break code = str(pref) + str(code) if request.method == 'POST': form = TransactionForm(request.POST) if form.is_valid(): product_ids = form.cleaned_data.get('product_ids', []) product_quantities = form.cleaned_data.get('product_quantities', []) subtotals = [] for product_id, quantity in zip(product_ids, product_quantities): product = Items.objects.get(id=product_id) product_price = product.price subtotal = quantity * product_price subtotals.append(subtotal) transaction = Transaction.objects.create(code=code) transaction.tendered_amount = request.POST.get('tendered_amount', 0) transaction.amount_change … -
Celery concurrency configuration for long tasks
I'm looking for the right configuration of celery to handle long tasks executed in django. These are the keys of the case: the tasks take several minutes to complete, but the processing is done in a remote server the worker procesing is minimal: it calls a remote API, waits for the response and updates a local database based on the response there are several types of tasks, each task type is enqueued to one queue depending on its type, the queues are dinamic, this is they cannot be defined initially the worker can only execute 1 task of each type. I assumed 1 only worker can manage all the tasks as its processing is low. This is the configuration I have so far: - CELERY_CREATE_MISSING_QUEUES = True - CELERYD_CONCURRENCY = 10 - CELERYD_PREFETCH_MULTIPLIER = 1 The worker is started this way, it should handle any queue: celery -A my_project worker --loglevel=info My celery app is defined this way: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') app = Celery('my_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -
Dynamically address lookup in Django template
I have a form on Django template with 2 fields: POSTCODE and HOUSE_NUMBER. I have a address_find() method in the related view. I need the full address to be displayed when the user fills in these 2 fields without submitting the form. ( In other words, when user enters POSTCODE and HOUSE_NUMBER, before submitting I want to check the address with address_find() method and display the full address under the form) Is it possible to do that in Django templates? or do I need to submit the form to do that? Thanks. -
How to split one video stream into several?
I have a code that outputs annotated images in django. Everything works except for one thing: the streams come from different cameras, but they are all displayed in one place. That is, a frame from one camera, then from another, then from a third. Three separate streams are needed for each. I guess I need to do something with it, return StreamingHttpResponse(generate_frames(), content_type='multipart/x-mixed-replace; boundary=frame') but I don't know what exactly. Help me please def video_stream(request): def generate_frames(): for i, result in enumerate(results): image = result.orig_img detection_results = model(image)[0] detections = sv.Detections.from_ultralytics(detection_results) detections = tracker.update_with_detections(detections) annotated_frame = process_frame(image, stream_index=i) # Pass stream_index to process_frame resized_image = cv2.resize(annotated_frame, (1024, 768)) _, frame = cv2.imencode('.jpg', resized_image) frame = frame.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') return StreamingHttpResponse(generate_frames(), content_type='multipart/x-mixed-replace; boundary=frame') -
django rest framework max_lenght CharField issue
I am trying to create a serializer to show a list of products in api_view. this list will include 3 things from my product model( their title, id, price). i use CharField for title with max_lenght=255 but i get and innit unknown_kwarg error for it. any solotions? class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) unit_price = models.DecimalField( max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField(validators=[MinValueValidator(0)]) last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion, blank=True) from rest_framework import serializers class ProductSerializer(serializers.Serializer): id = serializers.IntegerField() title = serializers.CharField() unit_price = serializers.DecimalField(max_digits=6, decimal_places=2) File "E:\python learning\storefront2\store\views.py", line 6, in <module> from .serializers import ProductSerializer File "E:\python learning\storefront2\store\serializers.py", line 3, in <module> class ProductSerializer(serializers.Serializer): File "E:\python learning\storefront2\store\serializers.py", line 5, in ProductSerializer title = serializers.CharField(max_lenght=254) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\.virtualenvs\storefront2-EzF46c-9\Lib\site-packages\rest_framework\fields.py", line 730, in __init__ super().__init__(**kwargs) TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght' After removing max_lenght, everything will work just fine! -
Disabling expiry check in simple-jwt package
We previously used the following setting in django-rest-framework-jwt package to disable token expiration check: 'JWT_VERIFY_EXPIRATION': False However now we are using django-rest-framework-simplejwt for authentication. How can we disable the expiry check in this package? I want to make sure that none of the existing tokens are invalidated because they are expired. -
Where to find information about django-serverside-datatables python module?
I'm trying to make a web page with Django and DataTables with a connection to my MySql database, and I found an interesting module called django-serverside-datatables. The thing is, at least maybe i can't find it, the creator doesn't give a properly explanation, or maybe, the module is as simple as that... Is there a page or someone that could give me more information about django-serverside-datatables? I don't want to use an, "objects.all" querySet, I want to literally use a connection to the database and do an sql query to take information, but I can't try to find information about that in the module... -
why does the slices read only the first and last line , skipping the line between them
I can't correctly capture (read) the text received from the user why is the data from the fill-in form not being read correctly? thank you in advance I can 't understand the reason , where did I make a mistake ? a = text.find("{") b = text.find("}") c = text.rfind("{") d = text.rfind("}") u = text.find("{") p = text.rfind("}") part_1 = text[0:a] part_2 = text[b + 1:c] part_3 = text[d + 1:u] part_4 = text[p:-2] text_message = part_1 + tg_name + part_2 + tg_phone + part_3 + tg_vacancy + part_4 desired result: Name : { name } Phone : { phone } Vacancy : { vacancy } output: Name : Jhon Phone : { phone } Vacancy : +359557664848courier -
JS pagination is detaching form inputs and breaking validation
The html: <div id="fs-table-content"></div> <div id="fs-table-pager"></div> The template: <script type="text/template" id="courseRowTemplate"> <div class="fs-table-row"> <div class="fs-table-cell" data-title="Course Name"> <input type="radio" class="radio" id="ssc-{0}" name="ss_course" value="{0}" required /> <label for="ssc-{0}">{0} </label> </div> <div class="fs-table-cell" data-title="Lesson"> {1} </div> </div> </script> I'm going with this form: FullScreenForm And a JS paginator class called SimplePaging1.0 (sorry can't find the link) but here is a screenshot of the page: When clicking a page, obviously the radio input elements get detached and replaced by the pager JS class, and when the FForm tried to validate upon clicking "continue to payment", it CAN'T because the radio inputs are no longer there. So I need a way to re-attach the inputs for the FForm class for validation. -
How can I retrieve the value from a method in Django's model?
How to retrieve value from a method in Django's model I have two models Model1 and Model2, Model2 is related to Model1. The method is located in Model2. The method name is get_organization_name class Model1(models.Model): code = models.CharField(max_length=5) random_id = models.IntegerField(primary_key=True) random_type = models.CharField(max_length=5) random_code = models.CharField(max_length=10) random_name = models.CharField(max_length=200) class Model2(models.Model): id = models.AutoField(primary_key=True) claim_id = models.PositiveIntegerField() random = models.OneToOneField('Model1', on_delete=models.DO_NOTHING, db_column='random_id', related_name='polis_journal') random_type = models.CharField(max_length=255) def get_organization_name(self): return polis_organizations.get(self.organization_id, None) I have tried following: queryset = Model1.objects.all() queryset = queryset.annotate(organization_name=F('polis_journal__get_organization_name') -
How to authenticated in subdomain app from parent domain app in django and reactjs
I have a parent domain, example.com, and a subdomain, app.example.com. If a user is already authenticated in the parent domain app, when they are redirected to the subdomain app, they should also be authenticated there. I am using ReactJS for the frontend and Django for the backend. For authentication in Django, I am using the third-party library drf-social-oauth2. I am new to this concepts. Thank you :) -
Django channel_layer can not get groups outside consumer
In AsyncJsonWebsocketConsumer I can get self.channel_layer.groups: print(self.channel_layer.groups) {'asgi__group__PUBLIC': {'asgispecific.bfba9fdb3232407bba13e25e775b2492'}} Outside consumer, in scipts: from channels.layers import get_channel_layer channel_layer = get_channel_layer() // The code working await channel_layer.group_send('PUBLIC', {'type': 'mark.price', 'data': {'price': 1}}) // But this not print(channel_layer.groups) {} What can I do to get groups outside consumer? TKS! channels 3.0.4 channels-redis 3.4.0 -
deploy node front end and python back end in heroku
I am a beginner to deploying apps, I have a NuxtJS front end and a Django back end that I want to deploy to Horku. I've looked at every tutorial and Stackoverflow post on how to achieve this, but everyone says to do the same thing which doesn't work. things I have tried: adding a Python and node build pack with adding the nuxt build to Django static files (tutorial I followed: https://github.com/mdrhmn/react-dj-todoapp/blob/master/README.md) that didn't work so I made docker images which I got successfully running locally but couldn't deploy to Heroku with heroku.yml file finally, I made two separate apps on Heroku and deployed each app separately which works fine but I don't like this solution Procfile(for the first option to deploy both together): release: python manage.py migrate web: gunicorn backend.wsgi --log-file - I tried adding both .ouput/server and output/public to Django static files which I can see in the Heroku bash note: if I change the web command to npm start the frontend would work but not the backend and vice versa I know that Heroku uses dynos and only exposes one port for the app but I don't know how to use that information to make it … -
Why does my video playlist on click not change to the video I selected . Via Javascript , Django, Python
The Playlist is supposed to let me click a video on the right and make it the main video, so you can watch it. The video scroller letting us know what time we are on the video also won't let me pick where I want the video to start. So if someone wanted to rewind you cannot. I think both these issues have to that i am using static files with django. I tried used the regular with t he src but i get no video at all. I am using Django, Javascript. HTML5 , CSS & Visual Studio Code. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>My Website</title> <link rel="icon" href="./favicon.ico" type="image/x-icon"> </head> <div class = "container5"> <div class="main-video-container"> <video {% load static %} src ="{% static "Chapter 3.1 Exercise 1-4.mp4" %}" loop controls class="main-video"></video> <h3 class="main-vid-title"> Properties of Parallel Lines Exercise 1-4</h3> </div> <div class="video-list-container" > <!-- This is where we keep adding videos to our list--> <div class="list active"> <video {% load static %} src="{% static "Chapter 3.1 Exercise 1-4.mp4" %}" class="list-video"></video> <h3 class="list-title">Properties of Parallel Lines Exercise 5-7</h3> </div> <div class="list"> <video {% load static %} src="{% static "Chapter … -
"Internal Server Error (500) during Sign-up in Django E-commerce Project"
I am currently working on a Django project, specifically an e-commerce application. However, I have encountered a problem during the sign-up process. The error message I'm receiving is "Failed to load resource: the server responded with a status of 500 (Internal Server Error)." For further assistance, please find the relevant code snippets and traceback information in the following files: urls.py, views.py, and related traceback. urls.py from django.urls import path from . import views app_name = "users" urlpatterns = [ path('', views.AccountView.as_view(), name="account"), path('profile', views.profile_view, name="profile"), path('sign-up', views.SignUpView.as_view(), name="sign-up"), path('sign-in', views.SignInView.as_view(), name="sign-in"), path('sign-out', views.sign_out, name="sign-out"), ] views.py from django.shortcuts import render, redirect, reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.conf import settings from django.http import JsonResponse from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from django.utils.decorators import method_decorator from django_google_api.mixins import( AjaxFormMixin, reCAPTCHAValidation, FormErrors, RedirectParams, is_ajax ) from .forms import ( UserForm, UserProfileForm, AuthForm, ) result = "Error" message = "There was an error, please try again" def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' class AccountView(TemplateView): ''' Generic FormView with our mixin to display user account page ''' template_name = "users/account.html" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def profile_view(request): ''' function … -
How to check the order of appearance on django test
I use this sentences to check the letters line1 and line2 appears. self.assertContains(response,"line1"); self.assertContains(response,"line2"); However I want to check the order of appearance. I checked in this page, but can't figure out which I should use. https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.SimpleTestCase.assertContains -
Django-simple-history: How do I access the historic values of m2m fields?
When accessing the historic data via historicObj = object.history.as_of([date in the past]) I get the historic values of all fields and all HistoricForeignKey. When accessing many-to-many fields I only get the current data. historicObj.m2m_field.all()[0].field = "newData" #not "oldData" Do I have to access it like this? historicObj.m2m_field.history.as_of([date in the past] This would complicate things. I hope I didn't miss anything obvious. Thank you in advance. (I use Python 3.8.10, Django 4.2.0 and django-simple-history 3.4.0 .) -
How to show level from Django MPTTModel in template?
I'm using django-mptt to store a hierarchical data (A Story with a number of scenes, in which each scene is a child of another scene) in DB. The data is for each node(scene) is collected from the user using a form. When the user is adding data to the form I like to show which level the current node is going to be saved. This is my model class Scene(MPTTModel, models.Model): story_id = models.ForeignKey(Story, on_delete=models.CASCADE, default=None) created_at = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=1000) choice1 = models.TextField(max_length=1000, default=None) choice2 = models.TextField(max_length=1000, default=None) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['id'] My forms.py class SceneForm(forms.ModelForm): class Meta: model = Scenario fields = ['description','choice1', 'choice2'] readonly_fields = ['level'] My scene.html {% extends "base.html" %} {% block content %} <h2>Create scene for Level {{form.level}}</h2> <h1>{{ form.title }}</h1> <p>{{ form.desc }}</p> <form class="scenario-designer" action="{% url 'App:designscene' %}" method="post"> {% csrf_token %} <table> {{form.as_table}} </table> <button type="submit" name="save" value="save">Save</button> </form> {% endblock %} The level is not showing, when I try form.level in debug console it shows AttributeError: 'SceneForm' object has no attribute 'level'. I was under the impression that since MPTTModel have level field it could be accessed using form.. Any pointers … -
Django inconsistent responses with graphene-django and django-multitenant custom set_current_tenant middleware
I've a django-multitenant SAAS with this tenant model: class Company(TenantModel): name = models.CharField( max_length=100, unique=True ) slug = AutoSlugField( populate_from='name' ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Companies' class TenantMeta: tenant_field_name = 'id' def __str__(self) -> str: return self.name I've setup a GraphQL api using graphene-django In my User model I've a ManyToManyField so the user can manage one or more companies. The goal is to have a company selector in the UI so the user can decide which company to manage. In order to accomplish that, I'm sending the tenant_id in the request headers and using a middleware (as suggested in the documentation) to execute the set_tenant_id() function. After trying many things I ended up with a setup that works perfectly in localhost: class SetTenantFromHeadersMiddleware: """ This Middleware works together with the next one (MultitenantGraphQLMiddleware). This one is responsible for setting the current tenant if the header was provided, this logic is here because for some reason in the MultitenantGraphQLMiddleware things differ as that's a GraphQL middleware: It gets executed once per field in the request and was randomly raising Company.DoesNotExist exception. """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path == … -
Display leaflet map coordinates in Django template from WKB POINT field in PostgreSQL database
I'm new to all things GEO. I have a WKB POINT field in a PostgreSQL database that stores locations. I also have a leaflet map on my Django template with hard coded lat and long added, which shows a working map on my front end. POINT example: 0101000020E610000051954507C62C1FC0144708B9E6784840 Can someone advise how I can decode the point field and insert the lat and long into my template so the map will update to the correct location from the database? If you need anything else like models just let me know. Any help appreciated. Template.html <div style="padding-top: 280px"> <h3 style="padding-bottom: 20px;">Location</h3> <script> function map_init_basic (map, options) { L.marker([11.5, 20.5]).addTo(map); map.panTo(new L.LatLng(11.737, 20.923)); } </script> {% leaflet_map "mymap" callback="window.map_init_basic" %} -
Why does my video playlist on click not change to the video I selected
The Playlist is supposed to let me click a video on the right and make it the main video, so you can watch it. The video scroller letting us know what time we are on the video also won't let me pick where I want the video to start. So if someone wanted to rewind you cannot. I think both these issues have to that i am using static files with django. I tried used the regular <video> </video> with the src but i get no video at all. I am using Django, Javascript. HTML5 , CSS & Visual Studio Code. The images go from top to bottom of my code , except the javascript is on a seperate file Top 1 Middle 2 Middle 3 End 4 JavaScript File on its own This is what it looks like in the development server -
Django Rest Framework receives Primary Key value in PUT request and returns "object not JSON serializable" error
I have a "Gift" model that has a user (the logged in user when the gift is created) and a receiver (which can be selected and changed by the user). My Gift model: class Gift(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=10, blank=True, null=True, validators=[validate_positive]) starred = models.BooleanField(default=False) user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='gifts_given') receiver = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='gifts_received', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): if not self.id or not uuid.UUID(str(self.id)): self.id = uuid.uuid4() super(Gift, self).save(*args, **kwargs) def __str__(self) -> str: if self.price: return self.name + ' $' + str(self.price) else: return self.name My Gift serializer: class GiftSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True) receiver = serializers.PrimaryKeyRelatedField(required=False, allow_null=True, queryset=CustomUser.objects.all()) links = serializers.SlugRelatedField(many=True, slug_field='url', read_only=True) class Meta: model = Gift fields = ( 'id', 'name', 'price', 'starred', 'user', 'receiver', 'links', 'created_at', 'updated_at' ) extra_kwargs = { 'id': {'read_only': True}, 'name': {'required': True}, 'user': {'read_only': True}, 'created_at': {'read_only': True}, 'updated_at': {'read_only': True}, } My Gift Views: class GiftList(generics.ListCreateAPIView): serializer_class = GiftSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Gift.objects.filter(user=self.request.user) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.validated_data['user'] = request.user self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) # TODO: Decide whether … -
Current URL anchor link gets added to my temple from Django Form Model ImageField
I've created an UserProfile. Facing an issue regarding ImageField. I had everything working fine on front-end until I added the image to my user profile from admin to test it. What I'm getting is anchor link which is a current URL of my user profile instead of getting a picture. I want help!! models.py from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from PIL import Image # Create your models here. class Profile(models.Model): slug = models.SlugField(max_length=255, unique=True, null=True) user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField('profile picture', default='accounts/avatars/default_avatar.jpg', upload_to="accounts/avatars/") bio = models.TextField(max_length=500, null=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): self.slug = slugify(self.user.get_username()) super().save(*args, **kwargs) img = Image.open(self.avatar.path) # Open image # resize image if img.height > 150 or img.width > 150: output_size = (150, 150) img.thumbnail(output_size) # Resize image img.save(self.avatar.path) # Save it again and override the larger image views.py @login_required def profile(request): if request.method == 'POST': p_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Your profile has been updated!') return redirect('home') # Redirect back to home page else: p_form = UpdateProfileForm(instance=request.user.profile) print(p_form.fields) context = { 'p_form': p_form } return render(request, 'accounts/profile.html', context) profile.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="profile-pic-wrapper"> <div class="pic-holder"> … -
The current path, =/login/, didn’t match any of these. Django
def loginPage(request): page = 'login' username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'user dose not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') context = {'page':page} return render(request, 'base/login_register.html', context) Here is the django code snippet of mine in the views.py file but it gives me an error saying, The current path, =/login/, didn’t match any of these. Django As i can see i have entered the correct path but it's not working Here is my urls.py file urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('register/', views.registerPage, name="register"), path('room/<str:pk>/', views.room, name="room"), path('create-room/', views.createRoom, name="create-room"), path('update-room/<str:pk>/', views.updateRoom, name="update-room"), path('delete-room/<str:pk>/', views.deleteRoom, name="delete-room"), path('', views.home, name="home"), ] I want to know the reason for the given error. -
Unable to Retrieve ForeignKey Objects in QuerySet
I’m just learning Django and i must say it is a very interesting framework. I'm facing an issue in my Django project where I'm unable to retrieve objects related to a ForeignKey field in a QuerySet. # models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) Now, I'm trying to retrieve all books by a specific author using a QuerySet: # views.py from django.shortcuts import render from .models import Author, Book def books_by_author(request, author_id): author = Author.objects.get(pk=author_id) books = Book.objects.filter(author=author) return render(request, 'books_by_author.html', {'books': books, 'author': author}) My template <!-- books_by_author.html --> <h1>{{ author.name }}'s Books</h1> <ul> {% for book in books %} <li>{{ book.title }}</li> {% endfor %} </ul> However, the books are not being displayed as expected. What might be causing this issue, and how can I correctly retrieve and display books related to a specific author in my template?