Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Select element options not opening on first click with Bootstrap
I have a html template with four selects. The same thing happens to me in all four. When I click on the select the first time it doesn't open, but after that, the following times it does. I want the options to be open the first time too. Los selects son así: <div class="input-group"> <select class="selectpicker" multiple data-live-search="true" id="src" name="src"> {% for value, label in jobs%} <option value="{{ value }}">{{ label }}</option> {% endfor %} </select> </div> The javaScript part is this. I have tried to do it in many ways but I can't. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script> <script> // Wait for the DOM to be ready document.addEventListener("DOMContentLoaded", function() { // Select all <select> elements var selectElements = document.querySelectorAll("select"); // Apply the Bootstrap Select plugin to each <select> element selectElements.forEach(function(selectElement) { console.log("DOM ready"); new bootstrap.Select(selectElement); }); }); </script> -
I inherited AbstractBaseUser, but my password is saved in plain text
My model is as follows. class Student(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=10, blank=True) id = models.CharField(max_length=10, primary_key=True) date_of_birth = models.DateField() gender = models.CharField(max_length=10) student_type = models.CharField(max_length=50) bio = models.TextField() email = models.EmailField(blank=False) phone = models.CharField(max_length=20, blank=False) is_selected = models.BooleanField(default=False) select_limit = models.PositiveIntegerField(default=0) select_count = models.PositiveIntegerField(default=0) groups = models.ManyToManyField(Group, related_name='%(class)s_groups') user_permissions = models.ManyToManyField(Permission, related_name='%(class)s_user_permissions') photo = models.ImageField(upload_to='student_photo/', default='student_photo/student_photo.png') USERNAME_FIELD = 'id' The results of my model creation are as follows enter image description here I hope my password is stored as ciphertext, so how can I solve it -
Displaying objects of several users in Django
I am coding network site and it has "Follow/Unfollow" function. When user follows X,Y users, there are following tab in the nav bar. There should be displayed all the posts of X,Y users the user has followed. Here is the view function: def following(request): currentUser = request.user users = currentUser.following.all() #Getting all the users the currentUser is followed to context = {"posts": postsOfFollowedUsers} return render(request, "network/following.html", context) How do I display all the posts related to several users? -
Deploying Angular-Django app on Hetzner Cloud - Cost-effective infrastructure for building scalable applications
I am looking to deploy my Angular-Django app on Hetzner Cloud and would like to get some insights and recommendations regarding the best practices and tools to use in this setup. I have chosen Hetzner Cloud for its cost-effectiveness and the need to build a scalable infrastructure for my application. Here's an overview of my deployment requirements and the technologies I am working with: Angular: Frontend framework for building the user interface. Django: Backend framework for implementing the business logic and API endpoints. PostgreSQL: Database management system for storing application data. Docker: Containerization technology for packaging my application and its dependencies. Nginx: Web server and reverse proxy for serving static files and routing requests. My goal is to achieve a reliable and scalable deployment, optimizing performance and minimizing costs. Specifically, I have the following questions: What is the recommended approach for deploying an Angular-Django app on Hetzner Cloud? Are there any specific tools or frameworks that work well in this setup? How can I leverage Docker for containerizing my application and managing its dependencies? Are there any best practices or considerations I should keep in mind? What is the suggested database setup for Django on Hetzner Cloud? Should I use … -
Django returns corrupted zip file
I wrote following code which fetches a data from db, forms two csvs, creates a zip containing both csvs and saves it to file system: import csv import io import zipfile from django.db import connection from models import MyModel myVal = 1019 with connection.cursor() as cursor: cursor.execute('''query''') query_result = cursor.fetchall() all_rows_result = MyModel.objects.filter(col1=myValue) # Create the zip file in memory zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, 'w') as zip_file: # Create the query result CSV query_data_csv = io.StringIO() query_data_writer = csv.writer(query_data_csv) query_data_writer.writerow(['col1', 'col2', 'col3', 'col4', 'col5', 'col6']) for row in query_result: query_data_writer.writerow(list(row)) zip_file.writestr('query_result.csv', query_data_csv.getvalue()) # Create the all rows CSV all_rows_csv = io.StringIO() all_rows_writer = csv.writer(all_rows_csv) all_rows_writer.writerow(['col1', 'col2', 'col3', 'col4', 'col5', 'col6']) for row in all_rows_result: all_rows_writer.writerow([row.id, row.course_id, row.url, row.ip_address, row.date_visited, row.user_id]) zip_file.writestr('all_rows.csv', all_rows_csv.getvalue()) with open('data.zip', 'wb') as zip_output: zip_output.write(zip_buffer.getvalue()) I ran above function and opened data.zip file. It contained two csv with desired data. The zip size was 4.1 kB. But when I opened, it shows one csv of size 2.0 kB and other of size 1.9 kB. Then, I converted this to django REST endpoint: import csv import io import zipfile from django.db import connection from models import MyModel from django.http import HttpResponse def get_user_tracking(request): myVal = request.GET.get('my_val') with … -
How can I annotate a calculated field into a Django queryset?
How can I get a calculated field into a queryset? Here is a code snipped: models.py: class Test(models.Model): field1 = models.CharField() @property def calc_field(self): return "hi" views.py: test = Test.objects.all() print(test[0].calc_field) # this works, but only in the backend test1 = Test.objects.all().values_list() print(test[0].calc_field) # this doesn't work, but this is what I get in the frontend If I pass this data to the frontend (Vue via Inertia) I can't access the calc_field anymore. Does anyone know how I can annotate the calc_field to the queryset? -
how to access a django sqlite3 database from command line?
I'm using an sqlite3 database for a django app, and it works correctly. I can print the version used with this code i wrote inside a view: # views.py import sqlite3 def my_view(..): connection = sqlite3.connect('C:/path/to/db.sqlite3') cursor = connection.cursor() cursor.execute('SELECT sqlite_version();') result = cursor.fetchone() sqlite_version = result[0] print("SQLite version:", sqlite_version) ... But if i run from command line python manage.py dbshell i get CommandError: You appear not to have the 'sqlite3' program installed or on your path. There are similar questions but the answers for example suggests to download sqlite3 which i don't think it makes sense because I can see that I already have a version installed Using: Django 4.2, Python 3.10.4, sqlite3 3.37.2. In a virtual environment. -
Access to XMLHttpRequest at 'http://localhost/api/get/' from origin 'http://localhost:3002' has been blocked by CORS policy in Django
I am trying to connect Django and React, I made an API in Django and calling that api from React app. But I am getting Access to XMLHttpRequest at 'http://localhost/api/get/' from origin 'http://localhost:3002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I know there are lots question on this topic, but none of those seem to solve in my case This is my settings.py file from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-(!kg*t#pzv!q6%xgap@)wg)dm8@lrtmh2x&f5yf5u15p7tmoc5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'analyzer_util.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'analyzer_util.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases … -
What do i set my STATIC_ROOT to when using django-storages, boto, boto3?
I am using linode object storage and django project deployed on a linode server. I have everything set up as far as the linode bucket and aws settings in my settings.py but what do I set my static_root to? STORAGES = { "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage" }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage" }, } LINODE_BUCKET = "my_bucket" LINODE_BUCKET_REGION = "us-east-1" AWS_S3_ENDPOINT_URL = f"https://{LINODE_BUCKET_REGION}.linodeobjects.com" -
Render Error: Cannot read property 'isLoggedIn' of undefined
I'm working with react native as front end and django as backend to create an app using expo. i'm using expo go which means i'm creating it directly on my mobile phone. the issue is my front end cannot read my backend api i get a render error that says: cannot read property 'isLoggedIn' of undefined. i've been stuck on this for 3 days i don't know what to do. i will appreciate every suggestions. `import React, { useState, useEffect, useRef, createContext } from "react"; import { SafeAreaProvider } from 'react-native-safe-area-context'; import Navigator from "../navigation/navigator"; const Context = createContext() const Provider = () => { const [ domain, setDomain] = useState("http://192.168.27.95:8000") const [ isLoggedIn, setIsLoggedIn ] = useState(false) const [ appSettings, setAppSettings ] = useState({}) function initAppSettings() { fetch(`${domain}/api/v1.0/app/settings`, { method: 'GET' }) .then(res => { if (res.ok){ return res.json() } else { throw res.json() } }) .then(json => { setAppSettings(json) }) .catch(error => { console.log(error) }) } useEffect(() => { initAppSettings() }, []) const globalContext = { domain, isLoggedIn, setIsLoggedIn, appSettings, setAppSettings, } return <Context.Provider value={globalContext}><SafeAreaProvider><Navigator /></SafeAreaProvider></Context.Provider> }; export { Context, Provider }; ` -
Django: Save inline form before run action
I'm using a django-inline-actions package for let end-users run actions in admin inlines. But it's no matter what exactly using for action button, i can implement it by hand (like this, for example), behavior will still the same. This look as: As provided by the django engine, the user does things like: Fill inline Click Save and continue button Click action button and he repeating it again and again, becouse users use action buttons very often. Is there any possibility for omit step 2? I think, it can be javascript hook, which capture click event, save inline data with ajax, and then run action. But i have no idea how implement it. May be there is another way to do it? -
Generate access token without code challenge and code verifier, with django rest along django-oauth-toolkit for OAuth access
I am trying to generate the access_token and refresh_token with Django rest framework and django-oauth-toolkit lib for the OAuth access delegation. I am trying to delegate the access to third party platform, where the third-party platform display the login button and when a user clicks the button it will open my website with response_type, client_id, scope, and redirect_uri. (all of these variable will be set on the third-party platform while setup). As per the django-oauth-toolkit documentation we also need to pass the code_challenge and code_challenge_method in the url while opening the login link, but third-party platform does not pass these 2 variables in the request. As per this documentations I am tryed by setting the PKCE_REQUIRED=False in the setting file of the project but getting an error of code_challenge in the response. Request URL http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=bG2Ju69XwS8jvnx3CWiobmWi1dj4kWsNYSiVsXEa&redirect_uri=http://127.0.0.1:8000/code/redirect/ Response http://127.0.0.1:8000/code/redirect/?error=invalid_request&error_description=Code+challenge+required. The authentication functionality is working with the code_challenge in the URL and able to generate the authorization_code Working example Request URL http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=bG2Ju69XwS8jvnx3CWiobmWi1dj4kWsNYSiVsXEa&redirect_uri=http://127.0.0.1:8000/code/redirect/&code_challenge=yCo4U9wZJPeYGyX3F6df_heuxG-6ZnvZfZB5KrCYpp4&code_challenge_method=S256 Response http://127.0.0.1:8000/code/redirect/?code=EAwEXghF807RTjxwyohky8psQKGohP I also tried with the OAUTH2_USE_PKCE = False in the setting file but not working. Thanks :) -
How can I resolve a 'MultipleObjectsReturned' error when integrating Razorpay payment in a Python Django application?
we integrated razor pay payment gateway our python Django application while making payment getting beloow error - MultipleObjectsReturned at /paymenthandler/abcd@gmail.com/2/ get() returned more than one book_history -- it returned 5! Request Method: POST Request URL: http://spandiagno.com/paymenthandler/abcd@gmail.com/2/ Django Version: 4.0.5 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one book_history -- it returned 5! Exception Location: /home/ubuntu/main/span_diagno/venv/lib/python3.10/site-packages/django/db/models/query.py, line 499, in get Python Executable: /home/ubuntu/main/span_diagno/venv/bin/python3 Python Version: 3.10.6 Expected to fix payment issue in razorpay. -
How to implement OpenID Connect with JWT id_token in Django allauth?
i use allauth Plugin for Django. I would like to give the users the possibility to log in to another provider. This offers OpenID Connect with JWT id_token. Can I solve this with allauth onboard or do I need my own provider? The goal is to register with this Provider and also login if the user is registered. With Google, Facebook ect. This works. i try to use openid_connect provider from allauth, but this is not JWT -
upload files to another shared hosting, with django
i have a django shared hosting(cpanel), but for storaging files coming from Front-end, i needed more space so i got an another shared-hosting(direct-admin) to upload files there, i connected the shared-hosting-storage to django-shared-hosting as a sub domain(in capnel with ip in ZoneEditor), like: http://dl.sabaol.ir, but i dont know how to upload files with django from django-shared-hosting to my shared-hosting-storage coming from front-end,i hope u guys to understand what i said :/ i googled so much about that , some said use ftp, is it right? if it is, but how? -
How do i Filtering the products by category using Ajax in django template
Here I'm trying to filter the products by category so I'm using the Ajax. So my problem is I have one shopt.html page in that page I filter the category that is displayed list wise and I click the radio button for the corresponding category I want to display the category-wise product... Model class Category(models.Model): main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE) name = models.CharField(max_length=100) View def filter_data(request): categories = request.GET.getlist('category[]') brands = request.GET.getlist('brand[]') allProducts = Product.objects.all().order_by('-id').distinct() if len(categories) > 0: allProducts = allProducts.filter(Categories__id__in=categories).distinct() if len(brands) > 0: allProducts = allProducts.filter(Brand__id__in=brands).distinct() t = render_to_string('ajax/shop.html', {'product': allProducts}) return JsonResponse({'data': t}) Here I'm trying to filter the products by category so I'm using the Ajax. So my problem is I have one shopt.html page in that page I filter the category that is displayed list wise and I click the radio button for the corresponding category I want to display the category-wise product... HTML <script> $(document).ready(function(){ $(".filter-checkbox").on('click', function(){ var filter_object={}; $(".filter-checkbox").each(function(index,ele){ var filter_value=$(this).val(); var filter_key=$(this).data('filter'); console.log(filter_key,filter_value); filter_object[filter_key]=Array.from(document.querySelectorAll('input[data-filter='+filter_key+']:checked')).map(function(el){ return el.value; }); }); $.ajax({ url:'{% url "filter-data" %}', data:filter_object, dataType:'json', success:function(res){ $("#filteredProducts").html(res.data); } }); }); }); {% endblock %} <form action="#"> {% for i in category %} <div class="single-widget-category"> <input type="checkbox" data-filter="category" id="{{i.id}}" value="{{i.id}}" class="filter-checkbox"> <label for="{{i.id}}">{{i.name}}<span>{{i.product_set.all.count}}</span></label> … -
How can I fix the AssertionError in my Django test case for image path generation in models?
I have created test case for generating the image path and added the function in the models for generating the image path I got the following error AssertionError: 'uploads\recipe\test-uuid.jpg' != 'uploads/recipe/test-uuid.jpg' uploads\recipe\test-uuid.jpg ? ^ ^ uploads/recipe/test-uuid.jpg ? ^ ^ @patch('core.models.uuid.uuid4') def test_recipe_file_name_uuid(self,mock_uuid): '''test generating image path''' uuid="test-uuid" mock_uuid.return_value=uuid file_path=models.recipe_image_file_path(None,"example.jpg") self.assertEqual(file_path,f'uploads/recipe/{uuid}.jpg') and the recipe_image_file_path in the models file is as follows def recipe_image_file_path(instance,filename): '''generating a file path for the new recipe image''' ext=os.path.splitext(filename)[1] filename=f'{uuid.uuid4()}{ext}' return os.path.join('uploads','recipe',filename) When I run test case I want to match the assertEqual(file_path,f'uploads/recipe/{uuid}.jpg') -
Why am I getting a Could not parse the remainder error when using AJAX with Django templates?
Here is my code using ajax in my code View def filter_data(request): categories = request.GET.getlist('category[]') brands = request.GET.getlist('brand[]') allProducts = Product.objects.all().order_by('-id').distinct() if len(categories) > 0: allProducts = allProducts.filter(Categories__id__in=categories).distinct() if len(brands) > 0: allProducts = allProducts.filter(Brand__id__in=brands).distinct() t = render_to_string('ajax/shop.html', {'product': allProducts}) return JsonResponse({'data': t}) Adding script to the HTML file {% block script%} <script> $(document).ready(function(){ $(".filter-checkbox").on('click', function(){ var filter_object={}; $(".filter-checkbox").each(function(index,ele){ var filter_value=$(this).val(); var filter_key=$(this).data('filter'); console.log(filter_key,filter_value); filter_object[filter_key]=Array.from(document.querySelectorAll('input[data-filter='+filter_key+']:checked')).map(function(el){ return el.value; }); }); $.ajax({ url:'{% url filter-data %}', data:filter_object, dataType:'json', success:function(res){ $("#filteredProducts").html(res.data); } }); }); }); </script> {% endblock %} URL path('shop/filter-data',filter_data,name='filter-data'), Got an unexpected eeror Error during template rendering Could not parse the remainder: '-data' from 'filter-data' url:'{% url filter-data %}' Got an error in my script tag So i changed the url to following the below code $.ajax({ url:'{% url 'filter-data' %}', data:filter_object, dataType:'json', success:function(res){ $("#filteredProducts").html(res.data); but got an error in the HTML file please check the below image Error image -
Making PyCharm default to Django tests runner
I have a Django project that works perfectly with PyCharm's Django tests Run/Debug config. For a particular project. how can I get PyCharm to default to Django test runner when clicking on a test method? When I click on the folder, the right click menu defaults to Django tests (as desired). ' When I click on a test method, the right click menu defaults to Python tests (not desirable, as my tests use Django). How can I force this to be Django tests? -
How to return a json object from html template back to views.py in django
In Django, how do I return a json object from html template back to views.py. The JSON object is an array of multiple JSON objects. I would like to return it back to the views.py file so that external get requests can be made to retrieve that JSON object. test.html <html> <head> <title>Test</title> <script> // Array to store JSON objects var jsonObject = { "data": [ {% for person in persons %} { "name": "{{ person.name }}", "weight": {{ person.weight }}, "height": {{ person.height }}, "date of birth": "{{ person.dob }}", }, {% endfor %} ] }; </script> </head> <body> <h1>JSON Objects:</h1> <pre id="personsDisplay"></pre> <script> document.getElementById("personsDisplay").textContent = JSON.stringify(jsonObject); </script> </body> </html> views.py def test(request): n = 10 # Replace with your desired value of N youngest_people = Persons.objects.filter( country=OuterRef('country') ).order_by('age')[:n] queryset = Persons.objects.filter( id__in=Subquery(youngest_peoples.values('birth')) ).order_by('country', '-age') context = { 'person': queryset } return render(request, 'test.html', context) The views.py is getting the top 10 oldest people from every country, passing that to the test.html to create the custom json object which is an array of the top 10 oldest people from every country json objects which shows their name, weight, height and date of birth. I then return that jsonObject back … -
many postgres.exe processes show on RAMMap with 4k private bytes
Here's my software environment OS: Windows Server 2016 version 1607 Database: PostgreSQL 12.12 Backend application: Django 4.0.8 RamMap: v1.61 I have memory leakage issue on this server and tried using RamMap to find out what's possibly cause this problem. As you can see in the attached image below, I have a lot of postgres.exe listing on the Processes page with pid and 4K Private bytes, but none of these shows up in Task Manager screen. All clients access PostgreSQL use http POST via my Django backend application installed on other server. I've tried some ways but fail: taskkill /f /pid <PID> did not work since they're not show in Task Manager. restart PostgreSQL service but theses zombie processes were still there. slow down clients access speed but these processes were still increasing. I have no idea how can I do to kill these processes. Could anyone give me some instructions to solve this problem? or the zombie processes is not even an issue that they will just there and have nothing to do with memory leakage? -
Pip instalation for Python 3.11 in docker
I have Dockerfile to build image for Django project that uses Python 3.11 and runs in poetry environment (see content below). Problem is when I try to donwload get-pip.py file and run it using Python, it says no such file or directory but it should be in the same directory where Dockerfile is. I don't know, but why isn't it there? P.S. I use docker desktop with WSL 2 (Ubuntu 20.04) and Dockerfile is in project directory (where poetry.lock and pyproject.toml files are), /website is directory where django project is. # Download image of Ubuntu 20.04 FROM ubuntu:20.04 # To prevent interactive dialogs ENV TZ=Europe \ DEBIAN_FRONTEND=noninteractive # Update and install necessary packages RUN apt-get update \ # Install necessary packages to allow compilation of source code && apt-get install -y --no-install-recommends \ tzdata \ build-essential \ checkinstall \ libreadline-gplv2-dev \ libncursesw5-dev \ libssl-dev \ libsqlite3-dev \ tk-dev \ libgdbm-dev \ libc6-dev \ libbz2-dev \ software-properties-common \ # Install python 3.11 && apt-get update \ && add-apt-repository ppa:deadsnakes/ppa \ && apt-get install -y --no-install-recommends \ python3.11 # Install pip for Python 3.11 RUN curl -sS -O https://bootstrap.pypa.io/get-pip.py | python3.11 # THERE'S AN ERROR RUN python3.11 get-pip.py # Install poetry ENV … -
Names of DJango admin form components
I am trying to re-arrange an admin form and add a button to do die rolling in the center of it. I'd like to keep the original functionality of controls. Most likely in another setting this would be done with some sort of java jiggery pokery but I'd rather just do it with django. I figure the simplest (if not easiest) way to get what I want would be to just do a custom admin form. But I am not sure what some of the controls are called so I've been having a time trying to find out how to set them up. Essentially this is a financial investment for a LARP I am involved in. Each Investment was done by a character (foreign key) against an institution (also foreign key). The player invests an amount of money. The staffer takes the money and rolls a die adding a modifier for the institution that is hidden from the player in a table and changes according to what is going on for that institution. If the die roll is X, they get Y result which determines if they lose their investment, get it back or make a profit. I want to … -
Django queryset for current week sales (not 7 days of sale - only sales for the actual week) getting naive datetime warning
I am trying to get current week sales for a particular vendor. It did works but a warning "created_at received a naive datetime (2023-05-28 00:00:00) while time zone support is active" keeps on bugging me. I know it is a warning but I really like to fix it. I tryed to format week_start and week_end to timestamp but it did not work. I also saw some answers on this issue using timezone, but I dont know if it is the best way do get rid of this warning. current_week_revenue = 0 # current week revenue week_start = date.today() week_start -= timedelta(days=week_start.weekday()) week_end = week_start + timedelta(days=6) current_week_orders = orders.filter(vendors__in=[vendor.id], created_at__gte=week_start, created_at__lt=week_end) Does anybody knows how to change this to get this warning away. The warning says it is a format matter but I am not being able to solve it. Thank you very much. -
Django template loop through dict and render it value below key
I'm using Django template to generate an HTML page in which I'm going through a dict, the key is an URL to a picture, the value is the caption to that image, what I'd like to render is in each row, the caption being right below the image, and render all entries (always four) in a dict in the same row, here's my code so far: <div class="grid grid-cols-2 gap-2 p-2"> {% for one_metric in url_list %} <ul> <tr> {% for url, caption in one_metric.items %} <td><img width="350" height="300" src="{{ url }}"></td> <td>{{ caption }}</td> {% endfor %} </tr> </ul> {% endfor %} </div> What ended up rendering is the caption listed on the right of the picture instead of being below it, I've searched through the Internet but didn't figure it out, any advice would be greatly appreciated!