Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert Django JSON field to Text in subquery
I have two models Assignment and Application. Assignment has meta field which has uuid data that is used to match uuid field on Application. My goal is to join assignee information when I query applications. I have some code like this using subquery. assignment_subquery = Assignment.objects.filter( meta__uuid=Cast(OuterRef('uuid'), TextField()) ).values('assignee__username')[:1] # Query applications and annotate them with the assignee's username applications_with_assignee = Application.objects.annotate( assignee_username=Subquery(assignment_subquery) ) It produce SQL like this SELECT "application"."id", "application"."uuid", (SELECT U1."username" FROM "assignment" U0 INNER JOIN "auth_user" U1 ON (U0."assignee_id" = U1."id") WHERE (U0."meta" -> 'uuid') = ("application"."uuid")::text LIMIT 1) AS "assignee_username" FROM "application"; It is almost correct except U0."meta" -> 'uuid' instead of U0."meta" ->> 'uuid', which I believe extracts the value associated with the specified key as text. I can't figure out how to get it to generate the right query. Thank you very much for helping. -
How to fix Console Error "CSS Stylesheet not loaded due to 'text/html' MIME mismatch" in Django 4.2?
I was just working on my website, and everyday the grand stylings worked fine and everything was up to good shape. But today, I went on Chrome and loaded my website first offline using the Django default server and it showed no styles, and I thought that it was just a WIFI issue. Once I connected, I saw the stylings didn't change and there are 2 MIME errors in my consoles for all the 3 browsers I tried it with (Microsoft Edge, Firefox, and Chrome). My static directories are setup properly, but for some reason when I tried to visit the stylesheet link to get a CSS file, I got 404 instead. I really don't know why this is happening. I tried doing some simple changes to my stylesheet, like removing any comments, and I even removed the rel='stylesheet' attribute to see what happened. Nothing worked. I went and did many Google searches, and even used the AI preview there, browsed through Stack Overflow, and read the documentation. I tried all their recommendations but nothing worked. Here is the code snippet for my tags and static setup in settings.py. <!-- HTML HEAD --> <head> {% block ex_head %} {% endblock … -
Django enable Multi-Tenant Social Login (tenants provide their own OAuth2 credentials)
I have a multi-tenant Django app created using the django-tenants package. My social login is handled by python-social-auth (more precisely drf_social_oauth2). I'd like to allow tenants to provide their own OAuth2 credentials (client_id & client_secret) and authenticate through their own Google / Azure apps. Is there any way I can inject tenants' OAuth2 credentials in ConvertTokenView() based on what schema the request is made from? Alternatively, I was thinking about dynamically modifying the following two settings.py settings: # these are global, but i'd like each tenant to have their own creds SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "<google_client_id>" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "<google_client_secret>" This alternative method does not work, because these settings are only read on Django server startup. -
Exclude objects with a related date range
Using these (simplified of course) models: class Person(models.Model): name = models.CharField() class InactivePeriod(models.Model) person = models.ForeignKeyField(Person) start_date = models.DateField() end_date = models.DateField() class Template(models.Model): day = models.CharField() #choices = monday, tuesday, etc... person = models.ForeignKeyField(Person) class TheList(models.Model): person = models.ForeignKeyField(Person) date = models.DateField(default=datetime.today) attended = models.BooleanField(default=False) I have a workflow where people call in to sign up for a daily event (there will be no online registration). Originally my users were going to enter each attendee manually each day as they call by creating a TheList record, and then check off if they attended. However, as each event has regulars that typically come on the same days. It was decided that I would provide a Template table, where the user could designate that 'Mike' is a regular on 'Monday' and then I would use a cronjob to automatically populate the TheList table with records for people who were regulars for that day. Then, my user interface is going to automatically filter the TheList list view down to the current day's attendees, and then my users can make any changes as necessary. It just reduces the amount of input they need to do. The wrinkle is that my users requested that … -
Django ModuleNotFoundError: No module named 'storages' despite package being installed
I'm encountering a persistent ModuleNotFoundError when trying to run my Django project, even though the package is installed. Here are the details: Problem When I run: python3 manage.py runserver I get the following error: CopyModuleNotFoundError: No module named 'storages' Environment: Windows 10 Python 3.10 Django (version unspecified) Virtual environment (houseVenv) What I've tried: 1 - I've confirmed that django-storages is installed: (houseVenv) PS C:\path\to\project> pip3 list | findstr storage django-storages 1.14.4 However, when I try to import it manually, it fails: Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'storages' 2 - I've tried uninstalling and reinstalling django-storages. 3 - I've verified that I'm in the correct virtual environment. 4 - I've checked that 'storages' is in my INSTALLED_APPS in settings.py. Why is Python unable to find the 'storages' module even though it's installed, and how can I resolve this issue? -
Error when deploying Django/DRF backend on Google Cloud: No matching distribution found for Django==5.0.4
I am trying to deploy my Django backend (using Django Rest Framework) on a Google Cloud VM instance. However, when I run pip install -r requirements.txt, I encounter the following error: Here are the steps I performed cd Project_Backend python3 -m venv env sudo apt-get install python3-venv python3 -m venv env source ./env/bin/activate pip install -r requirements.txt I am running Ubuntu on my Google Cloud VM. How should I resolve this issue and successfully deploy my Django application? -
Django ORM - .exclude Q vs exclude(ids_in=ids) with Subquery, annotate
Django Queryset exclude() not working as expected with Q expressions I'm trying to exclude some Project objects from my queryset using two different methods: one based on IDs and the other using a Q expression on annotated data. However, I'm getting different results from each approach, and I can't figure out why. The version with the Q expression returns an empty queryset, even though it shouldn't. Here's the relevant code: def check_exclusion(): # Subquery to get the latest active ReportCalculation message for each project latest_calc_message = ReportCalculation.objects.filter( project=OuterRef('pk'), is_active=True ).order_by('-id').values('message')[:1] # Annotate projects with the latest calculation message projects_with_messages = Project.objects.annotate( latest_message=Subquery(latest_calc_message) ).filter( end_date__lt=date.today(), # Project must have ended is_active=True # Project must be active ).distinct() # Exclude based on latest_message excluded_projects = projects_with_messages.filter( Q(latest_message__in=("Scheduled.", "Finished successfully.", "Processing ...")) | Q(latest_message__startswith="Error") ).distinct() ids = excluded_projects.values_list("id", flat=True) # Exclude using Q expression directly on the annotated field remaining_projects = projects_with_messages.exclude( Q(latest_message__in=("Scheduled.", "Finished successfully.", "Processing ...")) | Q(latest_message__startswith="Error") ).values('id', 'latest_message') # Get IDs and messages for verification print(projects_with_messages.exclude(id__in=ids)) # First method using IDs print(remaining_projects.values_list("id", flat=True)) # Second method using Q expression return list(excluded_projects), list(remaining_projects) What I'm observing: When excluding projects by IDs (i.e., exclude(id__in=ids)), the exclusion works as expected. When using the … -
Adding number line on scanned PDFs
This is a scanned PDF that I want to add some number lines and I have tried pytesseract, reportlab but am not getting the needed outcome. What I am looking for is below Here is my code, Its working with normal text PDF but not on scanned PDF import sys from collections import defaultdict from io import BytesIO from pypdf import PdfReader, PdfWriter from reportlab.pdfgen.canvas import Canvas # Initialize dictionaries to hold positions and sizes POSITIONS = defaultdict(lambda: sys.maxsize) SIZES = {} def record_line_positions(text, cm, tm, font_dict, font_size): """Record the positions of lines in the PDF.""" if not text.strip(): # Skip empty lines return x, y = tm[4], tm[5] # Extract x and y positions if POSITIONS[y] > x: # Record the leftmost x for each y POSITIONS[y] = x SIZES[y] = font_size # Store font size for the y position # Specify the paths to the original PDF and output PDF pdf_file_path = r'C:\PyCharm Projects\folder\media\20240925131414249.pdf' output_pdf_path = r'C:\PyCharm Projects\folder\media\text.pdf' # Open the original PDF file for reading with open(pdf_file_path, 'rb') as pdf_file: pdf_reader = PdfReader(pdf_file) pdf_writer = PdfWriter() # Iterate through each page for page_num in range(len(pdf_reader.pages)): page = pdf_reader.pages[page_num] POSITIONS.clear() # Reset positions and sizes for each page … -
Angular+Django CSRF token not being saved as cookie
I have a webapp with Angular frontend and Django backend. Everything works fine locally so I deployed the backend to PythonAnywhere. I use CSRF tokens so as soon the user opens the page, an empty request is sent to the backend, which responds with the token which is automatically saved as a cookie. However this does not work when I deploy the backend. I can see the token is in the response, but it does not appear in the browser storage, and it cannot be used for the following requests. I'm not sure how to even debug this. What could be causing this to begin with? This is the relevant part of my setttings.py: 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', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOWED_ORIGINS = ( 'http://localhost:4200', ) CSRF_TRUSTED_ORIGINS = ( 'http://localhost:4200', ) CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True I get the same problem when I deploy the frontend (then I also add it as a trusted origin but I skipped that in this extract). Like I said, I can see the token in the response in … -
Django Cart View: Total Amount Showing 0
I’m encountering an issue with my Django cart view where the total cart amount is showing as 0. Below are the relevant parts of my code and the logs. JavaScript (AJAX): $(document).ready(function() { $("#add-to-cart-btn").on("click", function(){ let quantity = $("#product-quantity").val(); let product_title = $(".product-title").val(); let product_id = $(".product-id").val(); let product_price = $("#current-product-price").text(); let product_image = $(".product-image").val(); let product_pid = $(".product-pid").val(); let this_val = $(this); // Log the values console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("PId:", product_pid); console.log("Image:", product_image); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); // Check if product price is valid if (!product_price || isNaN(parseFloat(product_price))) { console.error("Product price is invalid: " + product_price); return; } $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'pid': product_pid, 'image': product_image, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Go to Cart"); console.log("Added products to cart"); $(".cart-items-count").text(res.totalcartitems); $(".total").text(res.cart_total_ammount); } }); }); }); Django View: from decimal import Decimal, InvalidOperation from django.shortcuts import render, redirect from django.contrib import messages from .models import Coupon def cart_view(request): cart_total_amount = 0 coupon_discount_decimal = Decimal(0) coupon_code = "" coupon_discount_percentage = 0 if 'cart_data_obj' in request.session: print("Cart Data:", request.session['cart_data_obj']) # Log cart data for p_id, item in request.session['cart_data_obj'].items(): try: item_price = float(item['price']) except … -
When the page is fully loaded, the visibility limits part of the page
In the first option - page loading mode - this is if you interrupt it at the loading stage and not completely. The page is not completely loaded. In this case - option - all the content is displayed in the browser - the content that has time to load is loaded accordingly - which had time to load before the interruption. In the second option - page loading - this is if you do not interrupt the loading and the loading is complete. All the content on the page is completely loaded. But at the moment - immediately upon complete loading - there is a cut-off - a reduction in the visibility of the content - you cannot fully view the - seemingly fully loaded page. The content is cut-off. It is possible that something is not working somewhere. Could this be - is it because of the side menu? I'm trying to create a shell for Django Python. And I have a strange thing - visibility - content availability is limited. Although everything seems to load when loading - but then when fully loaded for some reason - there is a limitation - there is no scrolling of … -
Optimizing One-to-Many Relationships for Large Datasets in Sales Prediction
One to many relationships for huge dataset in an iteration? I tried to predict the future sales using store and product for which each store is mapping with all products which is taking huge time to process the data i tried batch processing and multi threads but still for 1200 stores and 750 products mapping takes 20-30 min which is too much for such small data set of 18000 rows how can i scale if i have huge data in millions.I want the process to happen in minutes for any amount of data even if it is taking too long for my processing. -
Possible to use axios to open page in new window in order to download csv from api view?
I have a Django view that downloads a large dataset from the database to a local .csv using StreamingHttpResponse. This works great; however, when I try to add authentication with [IsAuthenticated] permissions_classes tag, the url (of course) becomes unvisitable without including a valid user Bearer token in the header. Here is the relevant code from views.py: import csv from django.http import StreamingHttpResponse class Echo: def write(self, value): return value def streaming_csv_view(request): queryset = Emissions.objects.all().values_list('year', 'value') echo_buffer = Echo() csv_writer = csv.writer(echo_buffer) labels=[('Year', 'Value')] rows = (csv_writer.writerow(row) for row in chain(labels,queryset)) response = StreamingHttpResponse(rows, content_type="text/csv") response["Content-Disposition"] = 'attachment; filename="Emissions.csv"' return response I achieve this elsewhere in my code for more standard API calls (i.e. retrieving data), but can't wrap my head around how to make this work for my csv download, which requires that the user visit the page... Can I use an axios call to open this page in a new window to initiate the download and then close the window when the download is complete? I'm having trouble finding examples of axios being used in this way I feel like I'm missing something...any help would be greatly appreciated. Here's a typical axios GET request to the endpoint, which won't … -
where should i learn DJANGO? kindly help me out i am begginer in python backend web development. suggest me the best sources [closed]
where should i learn DJANGO from? kindly help me out i am begginer in python backend web development. suggest me the best sources for django. where should i learn DJANGO from? kindly help me out i am begginer in python backend web development. suggest me the best sources. -
Django Q tasks stuck in Queued
I think I have a broken task somewhere that is holding up all other scheduled tasks. Is there a way to delete all tasks in Django Q Queued Task list? I don't want to delete the actual ScheduledTasks but just the Queued instances? Is the a command that can be executed to quickly wipe them all as on the Django Admin panel I can only delete them in batches of 100 and there are thousands backed up. Thanks in advance -
Frozen day in Django form
I use django, nginx, gunicorn. Please help, this form records the date of record creation. For a long time everything worked fine, but recently the date was fixed at 2024-10-07, although it was 2024-10-09. The time on the server is correct. Restarting gunicorn helped, but now it records 2024-10-09. Can you indicate the reason for the failure? class MyForm(forms.ModelForm): create_date = forms.DateField(input_formats=['%Y-%m-%d'], widget=forms.DateInput(attrs={'type': 'date', 'value': (datetime.today() + timedelta(hours=3)).strftime('%Y-%m-%d'), 'readonly': True}), label='Create date') product_cost = forms.IntegerField(label='Cost') -
How can I serialize Cloudinary fields?
I'm trying to use Cloudinary SDK's for Svelte and Django. I have a model with CloudinaryField: class Room(models.Model): ... avatar = CloudinaryField("image") class UserRoom(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) ... and a serializer for the UserRoom: class UserRoomSerializer(ModelSerializer): user = UserSerializer() last_message = SerializerMethodField() def get_last_message(self, obj): return MessageSerializer(obj.room.message_set.first()).data class Meta: model = UserRoom fields = "__all__" depth = 1 I want to use Cloudinary's svelte component <CldImage /> and I need to pass an image public id into it. But when I make a request, I get an image path, not id: { "id": 1, "user": { ... }, "last_message": { ... }, "unread_messages": 0, "room": { "id": "49c33134-cc9f-43e0-b524-b05e9387602d", "name": "test", "avatar": "image/upload/v1728304120/sz8h5f5oqbtc95cfxbvx.jpg" // THIS LINE IS A PATH, NOT AN ID } } How do I make DRF send an id, not a path? -
Injecting input fields into existing HTML Form
Im trying to make a form which will be adding a new inputs whenever the user fill another input. I set up an event listener that will do ajax request into my back-end and, if succeed, it will bring an element of input that will be injected into the form. it looked like this : $.ajax({ type: "GET", url: "{% url 'cart:get-delivery' %}", data :{ city : id }, success: function(res) { $("#delivery").replaceWith(res.component) $('.spinner-overlay').remove(); }, error: function(e) { console.log("Failed") $('.spinner-overlay').remove(); } }) the form works on the surface, but when I submit the form, it won't recognize my newly added input fields. so when I do request.POST.get('example') it won't appear. does anyone have solution on this? also here is the added element : {% load humanize %} {% if content %} <td id="delivery"> {% for ins in content %} {% for jenis in ins.costs %} <div class="form-check"> <input class="form-check-input" type="radio" name="radio-delivery" id="{{ins.code}}" value="{{jenis.cost.0.value}}|{{ins.code}}|{{jenis.service}}"> <label class="form-check-label" for="radio-delivery"> <strong>{{ins.code | upper}}</strong> - {{jenis.service}} : Rp {{jenis.cost.0.value | intcomma}} </label> </div> {% endfor %} {% endfor %} </td> {% endif %} -
Django Issue After Migration: Identical Code in Test and Main Branch, But Production Fails
Has anyone encountered a similar issue in Django? In my test branch, everything works fine, including the password reset functionality. However, in production, it throws an error stating that the page doesn’t exist (even though it’s definitely there). I’m also experiencing a similar issue with date formatting. In test branch, the date displays correctly as the current month and year, but in production, it shows a different value, like “September 2020.” Any ideas on what could be causing this? I've reviewed the code in both the main and test branches, and everything appears identical. The issue began after the most recent migration, even though the site isn't used very often. Also if you will be wondering for some reason DEBUG = True And it's output specifically for the passwords was that the template was not found as I told you earlier. Any help would be highly appreciated! -
my chat user are not connecting each other
i am building a a private chat and calls both voice and video that preach privacy, with full privacy end to end, no message stored or saved to the backend, and every message is encrypted, so no one could breach it, every user has been given the power to thier own chat, now no matter what i do the chat isnt working i feel like my my consumer.py is not well written, i want user to chat and video call each other, but they are not chatting for example a user is not connecting with each other, its like they are not in a room together class SecureChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope['user'] self.friend_username = self.scope['url_route']['kwargs']['username'] if not self.user.is_authenticated: await self.close() return try: # Create a shared room name between both users for proper communication self.room_name = f"chat_{'_'.join(sorted([self.user.username, self.friend_username]))}" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.update_user_status(online=True) await self.accept() logger.info(f"WebSocket connection established for user {self.user.username} in room {self.room_name}") except Exception as e: logger.error(f"Error during WebSocket connection: {e}") await self.close() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_name, self.channel_name) await self.update_user_status(online=False) logger.info(f"WebSocket disconnected for user {self.user.username}") async def receive(self, text_data): """ Handle incoming WebSocket messages. Distinguish between message events and WebRTC events. """ try: data … -
Cant access image on aws-s3 saved via django
Url of image stored in db is: profile_pictures/f292ddfe-ee17-4ccc-be85-0398fb602753.jpeg but when i click on it, url becomes https://workandhomes.s3.amazonaws.com/media/profile_pictures/f292ddfe-ee17-4ccc-be85-0398fb602753.jpeg?AWSAccessKeyId={keyHere}&Signature={somevalue}&Expires=1728557943 these is my relevant code: models.py class UserProfile(models.Model): ... profile_picture = models.ImageField( upload_to="profile_pictures/", blank=True, null=True ) ... class Meta: db_table = "user_profile" settings.py .... # AWS S3 Configuration AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME") AWS_REGION = os.getenv( "AWS_REGION", "eu-north-1" ) # Replace 'your-default-region' with your region # Configure the default file storage to use S3 DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_REGION}.amazonaws.com/" ... I am able to perform the put operations and upload the file, but i cant read it. my IAM user on AWS as fullAccess to aws. and following is the bucket policy { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::workandhomes/*" } ] } Lastly when i remove the auth query strings, image opens. Any idea what is happening here ? -
my consumer.py is not working no matter what i do
i am building a a private chat and calls both voice and video that preach privacy, with full privacy end to end, no message stored or saved to the backend, and every message is encrypted, so no one could breach it, every user has been given the power to thier own chat, now no matter what i do the chat isnt working i feel like my my consumer.py is not well written. class SecureChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope['user'] self.friend_username = self.scope['url_route']['kwargs']['username'] if not self.user.is_authenticated: await self.close() return try: # Create a shared room name between both users for proper communication self.room_name = f"chat_{'_'.join(sorted([self.user.username, self.friend_username]))}" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.update_user_status(online=True) await self.accept() logger.info(f"WebSocket connection established for user {self.user.username} in room {self.room_name}") except Exception as e: logger.error(f"Error during WebSocket connection: {e}") await self.close() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_name, self.channel_name) await self.update_user_status(online=False) logger.info(f"WebSocket disconnected for user {self.user.username}") async def receive(self, text_data): """ Handle incoming WebSocket messages. Distinguish between message events and WebRTC events. """ try: data = json.loads(text_data) message_type = data.get('type') logger.info(f"Received message of type '{message_type}' from {self.user.username}") except json.JSONDecodeError as e: logger.error(f"Error parsing message data: {e}") await self.send_error("Invalid JSON format.") return if message_type == 'message': await self.handle_message_event(data) elif message_type … -
How to add the multiple image uploading feature in Wagtail?
I am primarily working with Django, Wagtail, and API serializers, without using templates directly for HTML rendering. Instead of HTML templates, I use Django's and Wagtail's API features to render content. Currently, I'm looking to add a new feature: multiple image uploading on the backend. Right now, with Wagtail, I can only upload a single image at a time. However, we need to modify this feature so that multiple images can be uploaded at the same time.. Let me clear my point my uploading a image. where the wagtail/images/muliple/add where user can add multiple images , but in default case we can only add one image at a time .What I need is for the ability to upload multiple images to be implemented in the default structure. my code structure is like this: ====================================== blocks.py: from wagtail.images.blocks import ImageChooserBlock from wagtail.models import Site, Page from cms.core.models import get_rootless_url_path import re from wagtail.images.models import Image from wagtail.templatetags.wagtailcore_tags import richtext class ImageChooserRenditionsAPIBlock(ImageChooserBlock): def get_api_representation(self, value, context=None) -> dict: from .serializers import ImageSerializer return ImageSerializer(value).data class GreeterBlock(StructBlock): label = TextBlock() # description = TextBlock() description =CustomRichTextBlock(features=['h1', 'h2', 'h3', 'h4', 'h5', 'bold', 'italic', 'ol', 'ul', 'hr', 'link', 'image', 'code', 'blockquote'] ) image = ImageChooserRenditionsAPIBlock(required=False) … -
Cache parts of the django template
I have a page, I want to cache only part of the template, because if I cache the whole page, I have the site header cached as well, and I don't need that. I tried to use the tag - cache in the template, but unfortunately the requests still keep going to the database. However, the cache is being accessed. What could be the problem? lesson.html {% extends "base.html" %} {% load static %} {% block content %} <div class="lesson-flex"> <div class="lesson-flex-nav"> {% for theme in selected_course.themes.all %} <div class="lesson-flex-nav-item"> <h1 class="lesson-flex-nav-title">{{ theme.name }}</h1> <ul class="lesson-flex-nav-list"> {% for lesson in theme.lessons.all %} <li><a href="{% url 'lesson_detail' course_slug=selected_course.slug lesson_slug=lesson.slug %}" class="lesson-flex-nav-list-item">{{ lesson.name }}</a></li> <div class="sep"></div> {% endfor %} </ul> </div> {% endfor %} </div> <div class="lesson-flex-wrapper"> <div class="lesson-flex-item"> <h2 class="lesson-flex-item-title">{{ lesson.name }}</h2> <div class="sep"></div> <p class="lesson-flex-item-text">{{ lesson.body|safe }}</p> </div> {% if lesson.questions.all %} <div class="lesson-flex-wrapper-questions"> <h3 class="lesson-flex-wrapper-questions-title">Questions</h3> <div class="sep"></div> {% for question in lesson.questions.all %} <div class="lesson-flex-wrapper-questions-item"> <p class="lesson-flex-wrapper-questions-item-title">{{ question.name }}</p> <details> <summary class="lesson-flex-wrapper-questions-item-legend">Answee</summary> <p class="lesson-flex-wrapper-questions-item-answer">{{ question.answer }}</p> </details> </div> {% endfor %} </div> {% endif %} {% if lesson.materials.all %} <div class="lesson-flex-wrapper-questions"> <h3 class="lesson-flex-wrapper-questions-title">Materials</h3> <div class="sep"></div> {% for material in lesson.materials.all %} <div class="lesson-flex-wrapper-questions-file"> {% if material.get_extension_display == '.zip' %} … -
Can't save BlobFields when using both django_gcp and django-reverse-admin
I'm trying to use both django-gcp to store large images as BlobFields, and django-reverse-admin so I can edit all of my data inline. My models look like this: class SceneContent(models.Model): site_title = RichCharField( max_length=25, verbose_name="Site Title (25 char)", null=True ) site_description = RichTextField( max_length=300, verbose_name="Site Description (300 char)", null=True, validators=[MaxLengthValidator(300)], ) site_image = BlobField( # blank=True, verbose_name="Site Image (3840 x 2160 px)", get_destination_path=get_destination_path_image, store_key="media", null=True, validators=[BlobImageExtensionValidator()], overwrite_mode="update", ) object_title_1 = RichCharField( max_length=25, verbose_name="Object Title 1 (25 char)", null=True ) object_description_1 = RichTextField( max_length=300, verbose_name="Object Description 1 (300 char)", null=True, ) object_image_1 = BlobField( # blank=True, verbose_name="Object Image 1 (3840 x 2160 px)", get_destination_path=get_destination_path_image, store_key="media", null=True, validators=[BlobImageExtensionValidator()], overwrite_mode="update", ) object_title_2 = RichCharField( max_length=25, verbose_name="Object Title 2 (25 char)", null=True ) object_description_2 = RichTextField( max_length=300, verbose_name="Object Description 2 (300 char)", null=True, ) object_image_2 = BlobField( # blank=True, verbose_name="Object Image 2 (3840 x 2160 px)", get_destination_path=get_destination_path_image, store_key="media", null=True, validators=[BlobImageExtensionValidator()], overwrite_mode="update", ) def __str__(self): return self.site_title class Site(models.Model): scene_title = RichCharField( max_length=12, verbose_name="Title (12 char)", null=True ) pronunciation_guide = RichCharField( max_length=25, verbose_name="Site Pronunciation Guide (25 char)", null=True ) scene_subtitle = RichCharField( max_length=40, verbose_name="Subtitle (40 char)", null=True ) scene_selection_image = BlobField( # blank=True, verbose_name="Background Image (1280 x 2160 px)", get_destination_path=get_destination_path_image, store_key="media", null=True, validators=[BlobImageExtensionValidator()], overwrite_mode="update", ) …