Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python send InMemoryUploadedFile to requests.request
In postmen I send data like this: My python code is: headers = { "Accept": "*/*", "Content-Type": "multipart/form-data; boundary=974767299852498929531610575", } response = requests.request( "POST", LINK, headers=headers, data={ 'product_id': 1, 'product_images': [file, ] } ) Where file has InMemoryUploadedFile format. But I've got error. Also I've tried file = my_file.file.getvalue() But still the error. How can I fix my cod and get 200 status? Any ideas? -
Wagtail view with URL params, or multiple custom URLs
I have a calendar that is used in a general Django app, but I also want to show it within the Wagtail app (which shows general text content/blog) for this site. I have got to the point where I can display the calendar on the Wagtail page, with some manual entry for the date params. The model for that looks like: class SchedulePage(PostPageExtras, RoutablePageMixin, Page): content_panels = Page.content_panels def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) context['schedule'] = self.get_calendar() return context def get_calendar(self): the_year = 2024 the_month = 7 cal = ScheduleCalendar().formatmonth(the_year, the_month, withyear=True) return cal I have tried to work this out with the RoutablePageMixin but didn’t make any progress. I can generate the_year and the_month values that derive from .now(), so the calendar always shows the current month. But I want the user to be able to navigate to next/previous months. The way that this is done in the Django app is that there are two urls that point to the same view, and the view interprets the parameters as required: path('/schedule/', views.ScheduleCalendarView.as_view(), name='control-schedule-calendar'), re_path(r'^/schedule/(?P<year>\d+)/(?P<month>\d+)/$', views.ScheduleCalendarView.as_view(), name='control-schedule-monthview'), With these two URLs you'll get the same page display (at July 2024): https://example.com/schedule/ https://examle.com/schedule/2024/07/ Because, in the first … -
Nested Serializers create method for each serializer
I have a Club Model as well as an Address model. class Club(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(UserAccount,on_delete=models.CASCADE,related_name = 'owner_of') ##members = models.ManyToManyField(UserAccount,related_name = 'member_of') ##staff = models.ManyToManyField(UserAccount,related_name = 'staff_of') def __str__(self): return f'{self.name}' class Address(models.Model): name = models.CharField(max_length=100) street = models.CharField(max_length=150) city = models.CharField(max_length=100) state = models.CharField(max_length=100, blank=True, null=True) # Optional for countries without states province = models.CharField(max_length=100, blank=True, null=True) # Optional for countries without provinces country = models.CharField(max_length=50) postal_code = models.CharField(max_length=20) club = models.ForeignKey(Club,on_delete=models.CASCADE,related_name = 'address') def __str__(self): return f'{self.name}' They have their respected serializers. class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ['id', 'name', 'street', 'city', 'state', 'province', 'postal_code', 'country'] def create(self,validated_data): user=self.context['user'] club=Club.objects.get(owner=user) address=Address.objects.create(club=club,**validated_data) return address class ClubSerializer(serializers.ModelSerializer): class Meta: model = Club fields = ['id', 'name'] def create(self,validated_data): user=self.context['user'] club=Club.objects.create(owner=user,**validated_data) return club class ClubRegistrationSerializer(serializers.Serializer): address= AddressSerializer2() club=ClubSerializer2() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # We pass the "upper serializer" context to the "nested one" self.fields['address'].context.update(self.context) self.fields['club'].context.update(self.context) this is the data that I am posting { "club":{"name":"someclub"}, "address":{ "name":"Bodrum Location", "street":"140", "city":"bodrum", "state":"california", "province":"some provence", "postal_code":"123", "country":"USA" } } I can easily implement the create method of my view and do this: @action(detail=False,methods=['post']) def register(self, request): serializer = ClubRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) clubinfo_data=serializer.validated_data.pop("club") club_serializer=ClubSerializer(data=clubinfo_data) club_serializer.is_valid(raise_exception=True) club=club_serializer.save(owner=self.request.user) … -
The BaseCommand command is not executed
from django.core.management import BaseCommand class Command(BaseCommand): help = 'Run parser' def handle(self, *args, **options): print('Hello!') I do not understand what this error is related to. The command "run_parser" should have started the parser in Django. -
How to pass list of integers as arguments for django's raw SQL, without formatting string
I'm struggling to figure out how to pass list of integer as arguments for Django's raw SQL without using f-string method. I have tried a simple method of def raw_query(self) -> str: return """select * from table where some_id in %s""" and call with (where ids are list of integer that I already wrap them as tuple) tupled_ids = tuple(ids) with connection.cursor() as cursor: cursor.execute(self.raw_query(), [ids]) Apparently, this wraps the argument with single quote, making them '(1,2,3)' instead of (1,2,3). Thus, syntax error. django.db.utils.ProgrammingError: syntax error at or near "'(1,2,3)'" I've also tried def raw_query(self) -> str: return """select * from table where some_id = any(%s)""" also give me similar error django.db.utils.DataError: malformed array literal: "(1,2,3,4,5)" LINE 2: ...om table where some_id = any('(1,2,3...` I've also tried with named params def raw_query(self) -> str: return """select * from table where some_id in %(ids)s""" with connection.cursor() as cursor: cursor.execute(sql=self.raw_query(), params={ "ids": tuple(ids) }) Still produce syntax error. Looks like django keep wrapping my list with quote. I feel like there must have been an obvious mistake but I can't really figure it out. There are other solutions that suggest to generate a place holder and use f-string to format the raw … -
How to track emails statuses
I am creating an SAAS email marketing system where users can create a company and run campaigns. Each campaign will have its own connected accounts (SMTP). Each user receives emails, which I send through smtplib. I then fetch the emails back using IMAP. I need to track the status of the emails, such as whether they are delivered, opened, or received an automated reply, etc. For all connected accounts that are linked with a company's campaign, the emails will be fetched and shown in the inbox. How can I determine that an email is a reply to a sent email and establish this relationship? How can I track the email status? Here is my model structure class SentEmail(models.Model): campaign = models.ForeignKey(to=Campaign, null=False, blank=False, on_delete=models.CASCADE) company = models.ForeignKey(to=Company, null=True, blank=False, on_delete=models.CASCADE) template = models.ForeignKey(to=EmailVariant, null=True, blank=True, on_delete=models.CASCADE) followup_template = models.ForeignKey(to=FollowUpEmail, null=True, blank=True, on_delete=models.CASCADE) contact = models.ForeignKey(to=Contact, null=False, blank=False, on_delete=models.CASCADE) connected_account = models.ForeignKey(to=ConnectedAccount, null=False, blank=False, on_delete=models.CASCADE) resend_id = models.CharField(max_length=250, null=True, blank=True) email_content = models.TextField(null=True, blank=True) email_sent = models.BooleanField(default=False) email_delivered = models.BooleanField(default=False) email_complained = models.BooleanField(default=False) email_bounced = models.BooleanField(default=False) email_opened = models.BooleanField(default=False) email_clicked = models.BooleanField(default=False) is_followup = models.BooleanField(default=False) is_lead_replied = models.BooleanField(default=False) is_automated_reply = models.BooleanField(default=False) is_positive_reply = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) objects = SentEmailManager() class … -
Errors crash the local development django cookie-cutter container
I've setup Django cookie-cutter for local development in Docker. It all works fine, even with VSCode devcontainer, changes are tracked and reloaded until there's a syntax or some other error. Then the entire container exits with code 1, which launches a cascade of errors in other containers that manage to stay alive while the django container remains dead :( It's all pretty much a generic django cookie cutter install with a few changes like: compose/local/django/start changed to: exec python manage.py runserver_plus --reloader-interval 3 --reloader-type stat 0.0.0.0:8000 watchdog dropped from local requirement, changed to: Werkzeug==3.0.3 Any hints how to reload changes, log errors but keep the container and server alive? Here's the container log for reference: 2024-07-10 13:57:55 Operations to perform: 2024-07-10 13:57:55 Apply all migrations: account, admin, auth, contenttypes, django_celery_beat, mfa, sessions, sites, socialaccount, users 2024-07-10 13:57:55 Running migrations: 2024-07-10 13:57:55 No migrations to apply. 2024-07-10 13:57:55 Your models in app(s): 'core' have changes that are not yet reflected in a migration, and so won't be applied. 2024-07-10 13:57:55 Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. 2024-07-10 13:58:01 Performing system checks... 2024-07-10 13:58:01 2024-07-10 13:58:01 System check identified no issues (0 silenced). … -
how can i fix vercel 404 not found i am working with django [closed]
404: NOT_FOUND Code: NOT_FOUND ID: fra1::ghmqv-1720609782490-787a6e7846dc how i can fix this error on vercel deployment script and screen shot of solutions contact me ifyou can ---------------------------------------------------------------------- -
The less than sign (<) does not work in my django template
The less than sign (<) does not work in my django template, it either treats it as html or it just does not work even if i try to do something simple like {% if 2<5 %}, the greater than sign works fine though I am using it for the paginator but its not working even for normal stuff as mentioned before As evident from the image above the < shows up in red, it does not work even for a simple operation. Here's the same code as text: {% for page in nums %} {% if forloop.counter >= 2 %} {% if forloop.counter == ticket_page.number ⅝} <li class="page-item active">a class="page-link" href="?page={{ forloop. counter }}">{{ forloop. counter }}</a></li> {% elif forloop.counter <= ticket_page-paginator.num_pages %} <li class="page-item"><a class="page-link" href="?page={{ forloop.counter }}">{{forloop. counter }}</a></li> {% endif %} {% endif %}{% endfor %} <!-- Dealing with the Next Pages --> -
Making a @property.setter an editable field in Django Admin Inlines
Documenting my solution here, maybe someone will have a better idea. In my current project, we have a calculated @property displaying a value based off criteria from other fields. Up until this point this was a readonly field so there was no issue with the regular django admin interface. Recently the client wanted to make this field editable (in my actual project it is displaying a DateTime); however, the values were being pulled from two different locations based on the data type and DB constraints. My first thought was to put both fields on the form and inject some JS to show/hide the relevant fields, but I wanted to see if this could be done with django. Going off of some answers I found here and here, I decided to go with a @property.setter and attempt to make it work with the Admin site, the additional context is that this form was currently being displayed in an Inline so I was unable to get either of those solutions to work for my situation. Inline forms... -
Edit entry URL not linking correctly in Django (Python crash course 3rd Ed.)
I'm working through the Python Crash Course book by Eric Matthes. In Chapter 19 i start to run into problems. The 'Edit Entry' section does not load correctly when clicking the link. The link displays where it should, with the text that it should, but when clicking the link i get this message in my browser: Page not found (404) Request Method: GET Request URL: http://localhost:8000/topics/1/%7Burl%20'learning_logs:edit_entry'%20entry.id%7D Using the URLconf defined in ll_project.urls, Django tried these URL patterns, in this order: admin/ [name='index'] topics/ [name='topics'] topics/<int:topic_id>/ [name='topic'] new_topic/ [name='new_topic'] new_entry/<int:topic_id>/ [name='new_entry'] edit_entry/<int:entry_id>/ [name='edit_entry'] The current path, topics/1/{url 'learning_logs:edit_entry' entry.id}, didn’t match any of these. runserver shows this output in the terminal: Not Found: /topics/1/{url 'learning_logs:edit_entry' entry.id} [10/Jul/2024 09:49:24] "GET /topics/1/%7Burl%20'learning_logs:edit_entry'%20entry.id%7D HTTP/1.1" 404 3357 Django Version 5.0.6 Python Version 3.12.4 Here is the relevant code i have so far in the project for reference: **learning_logs/views.py:** from django.shortcuts import render, redirect from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): ''' The home page for learning_logs ''' return render(request, 'learning_logs/index.html') def topics(request): ''' Show all topics ''' topics= Topic.objects.order_by('date_added') context= {'topics': topics} return render(request,'learning_logs/topics.html',context) def topic(request, topic_id): ''' Show a single topic and all it's entries ''' topic= Topic.objects.get(id=topic_id) entries= … -
How to wrap HTML around a block in django?
Similar to this question which didn't have an answer that works for me. I'm trying to customise allauth templates: email.html extends base_manage_email.html base_manage_email.html extends base_manage.html base_manage.html extends manage.html which I've overidden to extend my base layout. I want to wrap content as follows in base_manage.html: {% extends "allauth/layouts/manage.html" %} {% block content %} <div class="format"> {{ block.super }} </div> {% endblock %} This doesn't work though because I actually need something like {{ block.child }} to wrap where the child content (email.html) will be included. What actually happens is the contents of email.html is directly rendered as in my base.html. How can I simply add default formatting to all the allauth templates that extend base_manage.html? -
How to send authentication session id to django backend using fetch api?
saveBtn.addEventListener('click', function() { const csrftoken = getCookie('csrftoken'); fetch('http://localhost:8000/card/{{ auction.slug }}/add/', { method: 'GET', credentials: 'include', headers:{ 'Content-Type':'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken, }, }) .then(function(response) { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(function(data) { if (data.added === true) { saveBtn.innerHTML = 'Saved'; } else { saveBtn.innerHTML = ' Save'; } }) .catch(function(error) { console.error('Fetch request failed', error); }); }); function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.startsWith(name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } I am sending request to django backend via fetch api. When I try to retrieve the request user, TypeError: Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000184986CDE80>>. it returns an error Why django not authenticating using session id? Should I need to send request.user.id but if send that any user can make requests for other users I think. Or am I sending session id incorrectly to backend? views.py def add_to_card(request, slug): if request.user.is_anonymous: pass auction = get_object_or_404(Auction, slug=slug) user = request.user … -
Why session field is not being deleted in django Server sent event?
class task_check(AuthententicatedOrReadOnlyAPIView): content_negotiation_class = IgnoreClientContentNegotiation def get(self, request): timeout = int(request.query_params.get('timeout', 300)) task_id = request.session.get('pending_task_id') if not task_id: return HttpResponse("No pending task", status=404) def event_stream(): start_time = time.time() while True: if time.time() - start_time > timeout: del request.session['pending_task_id'] request.session.modified = True yield f"data: {json.dumps({'status': 'TIMEOUT'})}\n\n" break event_task_id = request.session.get('pending_task_id') if not event_task_id: yield f"data: {json.dumps({'status': 'TIMEOUT'})}\n\n" task = AsyncResult(event_task_id) if task.ready(): del request.session['pending_task_id'] request.session.modified = True yield f"data: {json.dumps({'status': 'DONE'})}\n\n" break else: yield f"data: {json.dumps({'status': 'PENDING'})}\n\n" time.sleep(5) # Check every 5 seconds response = StreamingHttpResponse(event_stream(), content_type='text/event-stream') response['Cache-Control'] = 'no-cache' response['X-Accel-Buffering'] = 'no' return response Now this code inside event_stream does not delete the pending_task_id for some reason, this lines execute as per the logic without error or warning but in next call to get of task_check , the session field pending_task id is as it is -
if my application is runing with docker compose how can I access localhost of within that application
I have a django application which run through docker compose on my local system on localhost:80. I have another application which runs at localhost:3000. I want to access http://localhost:3000 within the django application. While I try to access this I get the below error: ConnectionError at / HTTPConnectionPool(host='localhost', port=3000): Max retries exceeded with URL: /render (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1a03d7a610>: Failed to establish a new connection: [Errno 111] Connection refused')) If my question is vague or not clear please suggest what more information I can provide? -
How to check a generate code by simply-jwt
I try to verify a code generate by simply-jwt, but the second step when I tried to verify this, it's become False and I try to understand why the purpose it's to generate a code after login and verify this code in a second step here the views calls on the url: class ObtainAuthTokenStep1(TokenViewBase): serializer_class = AuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): user = serializer.validated_data['user'] # Generate a 2FA code and secret secret = base64.b32encode(SECRET_KEY.encode()).decode() totp = pyotp.TOTP(secret) verification_code = totp.now() send_verification_code_via_email(user, verification_code) # Generate a code token with the secret embedded refresh = RefreshToken.for_user(user) refresh['totp_secret'] = secret code_token = str(refresh.access_token) response_data = { 'code_token': code_token, 'message': 'Verification code sent to your email.' } return Response(response_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and the serializers for the check: class AuthTokenStep2Serializer(serializers.Serializer): code_token = serializers.CharField() code = serializers.CharField() def validate(self, attrs): code_token = attrs.get('code_token') code = attrs.get('code') if code_token and code: decode_token(code_token) secret = base64.b32encode(SECRET_KEY.encode()).decode() totp = pyotp.TOTP(secret) if not totp.verify(code): raise serializers.ValidationError(_('Invalid code.')) else: raise serializers.ValidationError(_('Must include "code_token" and "code".')) return attrs If I do the same thing in a terminal I don't have any problem and the sending code work well -
Wagtail/Django Taggit - Unique Tag pool for each set of child pages
For the sake of example, let's say we wanted to create multiple blogs, but in the same app. Each blog has blog posts that are children of each respective blog. Is there away to set up Taggit so that each blogs pool of tags remain separate from each other. Say if one is a food blog, and the other is a car blog, you don't want auto-completion suggestions from one showing up on the other. I have attempted the "Custom Tag Models" example on the Wagtail docs here. With no luck. I've also tried the suggestion on this stackoverflow question. Here is the code from the Wagtail docs above: from django.db import models from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.fields import ParentalKey from taggit.models import TagBase, ItemBase class BlogTag(TagBase): class Meta: verbose_name = "blog tag" verbose_name_plural = "blog tags" class TaggedBlog(ItemBase): tag = models.ForeignKey( BlogTag, related_name="tagged_blogs", on_delete=models.CASCADE ) content_object = ParentalKey( to='demo.BlogPage', on_delete=models.CASCADE, related_name='tagged_items' ) class BlogPage(Page): ... tags = ClusterTaggableManager(through='demo.TaggedBlog', blank=True) Thanks in advance! -
How do I make ApolloClient use multipart/form-data when sending requests to django graphql endpoint
I am writing a Django/GraphQL/Apollo/Vuetify app, and I am struggling to navigate the CORS/CRSF consequences. As far as I understand, I think that Django and GraphQL are doing the right thing on the backend with regard to CORS and CRSF. When I use the python requests library, I can successfully send a request to the graphql endpoint and get a response. To do this, I send a POST request with Content-Type multipart/form-data and make sure that data contains the correct csrfmiddlewaretoken value. @when(u'we execute the GraphQL query "{query}"') def step_impl(context, query): context.response = context.rest_client.post("/graphql/", data={"query": query}) def post(self, path, **kwargs): csrftoken = self.session.cookies.get('csrftoken') if 'data' in kwargs and csrftoken: kwargs['data']['csrfmiddlewaretoken'] = csrftoken return self.session.post(url(path), **kwargs) However, ApolloClient insists on sending the query using application/json and not multipart/form-data. As a result, I cannot add the csrfmiddlewaretoken field to the request payload, and I get a 403 Forbidden response. I've followed the steps outlined in https://apollo.vuejs.org/guide-option/setup.html import { registerPlugins } from '@/plugins' import mitt from "mitt" import { ApolloClient, InMemoryCache } from '@apollo/client/core' const cache = new InMemoryCache() const apolloClient = new ApolloClient({ cache, uri: 'http://localhost:8000/graphql/', credentials: 'include' }) import { createApolloProvider } from '@vue/apollo-option' const apolloProvider = createApolloProvider({ defaultClient: apolloClient, }) … -
No Module Found (import cloudinary) - Django Heroku
import cloudinary_storage import os import ssl import certifi import dj_database_url anytime i try to deploy to heroku, it deploys successful but the page says Application error and cloudinary module not found. I use VSCode and the import cloudinary_storage greys out and i have done everything i could do and still not working, same with import cloudinary I have set my CLOUDINARY_STORAGE and DEFAULT_FILE_STORAGE also. I uninstalled and also install cloudinary and included it in the requirements.txt, same problem occurs -
How do I create a REST API for a project for a hackathon using django which I have no experience of?
I have to create a REST API for a project in django for a hackathon, I have never created one. I have worked on basic django projects but have not built an api. I tried following along a tutorial but the demo project of the tutorial is very different. I have less time how do I approach it -
I have problems loading a machine learning model on my Django site
I've build an image classification model that classifies images as one of three classes: cucumber, zucchini, or neither. Now I want to deploy this model to a Django website but I am currently experiencing some problems. When I run the python manage.py runserver command I get the following printed in the terminal: Watching for file changes with StatReloader Performing system checks... 2024-07-10 01:26:11.875397: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`. 2024-07-10 01:26:12.947630: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`. C:\path\to\virtual\environment\virtual_environment_name\Lib\site- packages\keras\src\layers\preprocessing\tf_data_layer.py:19: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead. super().__init__(**kwargs) 2024-07-10 01:26:14.748468: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags. Now, to me this does not appear … -
Display just 10 pages for pagination with django
Im working on a django pagination and its okay but next and previous buttons in django pagination just skip 1 page. I want that django pagination show number 1 to 10 pages for pagination at first and then when i click on next button it goes to page 11 and shows another 10 numbers, 11 to 20. And when i click on next again it goes to page 21 and shows numbers 21 to 30. And it would be the same for previous button. How to make django pagination like that? -
How to run function at startup before requests are handled in Django
I want to run some code when my Django server starts-up in order to clean up from the previous end of the server. How can I run some code once and only once at startup, before the server processes any requests. I need to access the database during this time. I've read a couple of things online that seem a bit outdated and also are not guaranteed to run only once. -
Django error: Reverse for 'user_workouts' not found. 'user_workouts' is not a valid view function or pattern name
I'm working on my project for a course and I'm totally stuck right now. I'm creating a website to manage workouts by user and the create workout do not redirect to the user's workouts page when I create the new workout instance. views.py # View to return all user's workouts def user_workouts(request, user_id): user = User.objects.get(id=user_id) print(user) workouts = get_list_or_404(Workout, user=user.id) return render(request, "users/workouts.html", {"user": user, "workouts": workouts}) # Create workout view def add_workout(request, user_id): user = get_object_or_404(User, id=user_id) print(user) print(request._post) if request.method == "POST": workout_title = request.POST.get("workout") reps = request.POST.get("reps") load = request.POST.get("load") last_update = request.POST.get("last_update") workout = Workout(workout=workout_title, reps=reps, load=load, last_update=last_update, user=user) workout.save() print(user.id) return redirect('user_workouts') context = {"workout": workout} return render(request, "users/add_workout.html", context=context) urls.py from django.urls import path from . import views app_name = "myapp" urlpatterns = [ path("", views.index, name="index"), path("user/<int:user_id>", views.user_detail, name="user_detail"), path("user/<int:user_id>/workouts", views.user_workouts, name="user_workouts"), path("user/<int:user_id>/workouts/<int:workout_id>", views.workout_detail, name="workout_detail"), path("user/<int:user_id>/workouts/Add Workout", views.open_workout_form, name="open_workout_form"), path("user/<int:user_id>/workouts/create/", views.add_workout, name="add_workout") ] -
Django templates and css: is there a workaround for getting my preload link tags to match my css relative paths to font sources?
Background I just started using Digital Oceans Spaces for storing my static files for my Django web app (connected using django-storages library). Previously, I used link elements in the head of my base template to preload my fonts to avoid font-switching flashes while the page is loading (which is the case for 'Mona Sans') or when an element that uses a custom font is shown for the first time (I use a 'Pixelated' font in a dialog element). The Issue However, now there is a discrepancy in the url's produced by the static template tag in my Django templates and the url's produced by relative paths in my css file. The fonts get loaded just fine using the relative path in the css file, but they are missing the query parameters, so the preloaded resources (with query parameters) don't actually end up being used (causing brief font-swap flash and console warnings). Additionally, I don't know if not having the query parameters will eventually cause issues once I implement read-protection with pre-signed URLs. Django template <link rel="preload" href="{% static 'fonts/Mona-Sans.woff2' %}" as="font" type="font/woff2" crossorigin/> <link rel="preload" href="{% static 'fonts/Pixelated.woff2' %}" as="font" type="font/woff2" crossorigin/> This use of the static tag results in …