Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Azure Web App receiving 'Bad Request (400)' when accessed via the custom domain but works with the Azure provide default domain
I am deploying a Django Azure Web App and have added a custom domain that I bought off GoDaddy to it. I have also bound an SSL certificate provided by Azure to it. When I access the website via the default Azure domain, I'm able to access it but from the custom domain the server returns a 400 Bad Request. I've added to the list of CSRF_TRUSTED_ORIGINS as well as ALLOWED_HOSTS list the default domain as well as the custom domain. I have selected from the configuration on Azure Web App the option to redirect HTTP request to HTTPS. I have also added the DNS records (A and TXT) in GoDaddy to point to the server's public IP. May I have suggestions on things I could do to get it working? I am a novice at this and it's my first time setting up a website. I tried the following HTTPS settings in the settings.py file but it hasn't worked out, and I'm not too sure if I'm approaching it right either, thought I'd give it a go. SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True X_FRAME_OPTIONS = 'DENY' … -
VS code Python Django debugger dont stop on breakpoints
Config: "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/anfisa1sprint-master/anfisa_for_friends/manage.py", "args": [ "runserver" ], "justMyCode": false, "stopOnEntry": true, "django": true, "autoStartBrowser": true } ] } When i start debugger it starts the server, but i dont see any information in logs when i browse http://127.0.0.1:8000/ no logs at all about requests, status codes etc in the terminal. When i trying to trigger view (via visiting http://127.0.0.1:8000/about/ for example) it does not stop at breakpoints at all but opens the page on browser correctly -
Redirecting after making PUT request: can I redirect with GET request instead?
For my Django project, I have a primary model, Book, and an associated BookViewSet (from Django REST Framework). From the frontend, it's possible to edit other objects like Page, which POSTs to a corresponding PageViewSet. Changes to Page objects will also affect the Book, so I want to return an updated BookViewSet after processing changes to the Page. After processing a PUT request for the Page via the PageViewSet, I've tried leveraging the redirect shortcut to send the request to the BookViewSet, like this: return redirect('/books/10', pk=book_id) I expected (and hoped) this would make a GET request so that the backend would return an updated Book via the BookViewSet using the "retrieve" method. However, it seems like the BookViewSet still receives PUT request, which means the request will be sent to the BookViewSet's "update" method. Is this expected? If so, is there a way I can "get" an updated Book view after making changes to Page? I can achieve this by putting that logic into the BookViewSet's "update" method, but I already have that logic in the "retrieve" method and don't want to duplicate it. I recently found this pattern described as "post, redirect, get" and am not sure if … -
migrations.RunPython are not executed during pytest tests
I have a Django migration: # Generated by Django 3.2 on 2024-10-15 11:05 import django.db.models.deletion from django.conf import settings from django.db import migrations, models def populate_recognition_states(apps, schema_editor): RecognitionState = apps.get_model('masterdata', 'RecognitionState') RecognitionState(code='recognition', name='Recognition').save() RecognitionState(code='timeout', name='Timeout').save() def populate_recognition_settings(apps, schema_editor): raise RecognitionSettings = apps.get_model('masterdata', 'RecognitionSettings') RecognitionSettings(waiting_time=300).save() class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.CreateModel( name='RecognitionSettings', fields=[ ('id', models.AutoField(...), ('waiting_time', models.PositiveIntegerField()), ], ), migrations.CreateModel( name='RecognitionState', fields=[ ('id', models.AutoField(...), ('code', models.CharField(...)), ('name', models.CharField(...)), ], ), migrations.RunPython(populate_recognition_settings), migrations.RunPython(populate_recognition_states), ] The problem with it is that populate_recognition_settings and populate_recognition_states are not being ran during pytest tests. You could notice that inside populate_recognition_settings there is raise but nothing fails. Deps: pytest 7.2.0 pytest-cov 3.0.0 pytest-django 4.5.2 pytest-forked 1.3.0 pytest-mock 3.6.1 pytest-xdist 2.2.1 Django 3.2 Why data migrations are not being applied? And how to fix it? -
Django (s3) doesn't use custom domain for statics
I have S3 object storage with a CDN infront of it (on DigitalOcean). I have pointed my domain cdn.domain.com to the cdn & this is working fine. In Django I am using django-storages[s3] to connect with S3 and store static files. This works and static files are being transferred to my bucket on running collectstatic. Whenever I try to access any file the url doesn't get built properly. On localhost it looks like this http://127.0.0.1/http//cdn.domain.com. I have a modified implementation of the S3Storage to automatically handle ACLs based on my configuraton. import fnmatch from django.conf import settings from storages.backends.s3 import S3Storage class StorageBackend(S3Storage): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.default_acl = getattr(settings, "AWS_DEFAULT_ACL", "private") self.default_cache_control = getattr( settings, "AWS_S3_OBJECT_PARAMETERS", {} ).get("CacheControl", "max-age=86400") self.public_folders = getattr(settings, "S3_PUBLIC_FOLDERS", {}) def _save(self, name, content): self.default_acl = self._get_acl(name) self.object_parameters = {"CacheControl": self._get_cache_control(name)} return super()._save(name, content) def _get_acl(self, name): for folder, config in self.public_folders.items(): if self._match_pattern(name, folder): if "files" not in config or not config["files"]: return "public-read" for pattern in config["files"]: if self._match_pattern(name, pattern): return "public-read" return "private" def _get_cache_control(self, name): for folder, config in self.public_folders.items(): if self._match_pattern(name, folder): if "cache" in config: if "files" not in config or not config["files"]: return config["cache"] for pattern … -
How can I use if else statements with multiple blocks in Django templates?
I want to load different meta tags based on the context data I receive. As you can see, in case 1, I retrieve the name from '2. name', while in case 2, it comes from 'name'. When I use this if-else statement, I encounter an error stating that the use of multiple blocks is not allowed. {% extends 'base.html' %} {% load static %} {% load custom_filters %} {% if context.api_name == 'case 1' %} {% block meta_keywords %} <meta name="keywords" content="some keywords"> {% endblock %} {% block meta_description %} <meta name="description" content="{{ context.json_data | get_key:'2. name' |default:'Unknown' }}"> {% endblock %} {% elif context.api_name == "case 2" %} {% block meta_keywords %} <meta name="keywords" content="some keywords"> {% endblock %} {% block meta_description %} <meta name="description" content="{{ context.json_data | get_key:'name' |default:'Unknown' }}"> {% endblock %} {% endif %} TemplateSyntaxError django.template.exceptions.TemplateSyntaxError: 'block' tag with name 'meta_keywords' appears more than once I also tried using with to set temporary variables, but I couldn't get it to work -
Django pagination "infinity scroll" with HTMX incorect insert order
I'm trying to implement pagination known as "infinite scroll" with HTMX. All works fine except ordering of newly inserted objects not always correct. For example if view paginate_by = 10 then first 10 objects ordered as expected and next 10 objects will be inserted with some order failures: 7-8 object are ordered as expected and rest 2 object which supposed to be on top of the table inserted in the end. View: class ShippedProductListView(ListView): model = models.Product context_object_name = "products" paginate_by = 10 ordering = ['-shipment__shipment_date'] def get_queryset(self): queryset = models.Product.objects.filter(status=models.ProductStatus.SENT) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['total_count'] = self.get_queryset().count() return context HTML: <table> <!-- some content here --> <tbody> {% include "production/shipped_products_table.html" with products=products %} <!-- Shipped products table updates with htmx --> </tbody> </table> shipped_products_table.html: {% for d in products %} {% if forloop.last %} <tr hx-trigger="revealed" hx-get="{% url 'shipped_products_list' %}?page={{ page_obj.number|add:1 }}" hx-swap="afterend" h > {% else %} <tr> {% endif %} <tr> <td><a class="link-success" href="{% url 'products_detail' sn=d.serial_number %}">{{ d.serial_number }}</a></td> <!-- some more content here --> </tr> {% empty %} <h5 class="pt-4">Nothing here yet.</h5> {% endfor %} Is that a normal behavior or I'm missing something? -
Problem running Django crontab in Docker container
I'm trying to create a simple cron, in my django application, but despite adding and launching correctly, the cron doesn't execute, nor does it save logs settings.py INSTALLED_APPS = [ 'django_crontab', ] CRONJOBS = [ ('*/1 * * * *', 'myapp.cron.test_func', '>> /var/log/cron.log 2>&1'), ] Dockerfile python:3.12 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt . RUN pip3 install --upgrade pip RUN pip3 install --no-cache-dir -r requirements.txt RUN apt-get update && \ apt-get install -y cron && \ apt-get clean RUN touch /var/log/cron.log docker-entrypoint.sh python3 manage.py crontab add service cron start exec "$@" When the container is launched, the commands return these results: crontab -l */1 * * * * /usr/local/bin/python3 /app/manage.py crontab run <cron_id> >> /var/log/cron.log 2>&1 # django-cronjobs for my_project python3 manage.py crontab show <cron_id> -> ('*/1 * * * *', 'myapp.cron.test_func', '>> /var/log/cron.log 2>&1') service cron status cron is running. Manually running cron with the command “python3 manage.py crontab run <cron_id>” works fine, the logs are empty. -
Coda docs webhooks and django
I am building a web application with Django and I'm trying to automate the fetching of new data from Coda Docs. I want to use web hooks so that when rows are added on the Coda docs, my code for fetching the new data is executed. Already, I have a scheduled task that works, but I'd like to just switch to web hooks as it is automatic. I am confused on how to go about this. I don't understand what I'm reading online on Coda API regarding this. I don't even understand the step 1 and step 2 set up. I tried using match.com and despite providing my api key with read and write access it couldn't fetch the table. How would one go about writing Django code for implementing web hook that triggers retrieval of the latest data from Coda docs once a change has been made on the table? -
Dynamically Show/Hide Django Admin Inline Forms Based on Dropdown Selection
I'm trying to dynamically show and hide inline forms in the Django admin based on a dropdown selection. I have two inline forms: one for IndividualCustomer and another for CorporateCustomer. The goal is for the corresponding inline to appear when a specific customer type is selected from the dropdown. Here’s what I’ve set up: Models: I have defined IndividualCustomer, CorporateCustomer, and Customer models. Admin: I've created inlines for both customer types and included them in the CustomerAdmin class. Custom Template: I’m using a custom change_form.html to implement the JavaScript logic. Models and Admin Code: # models.py from django.db import models class Customer(models.Model): CUSTOMER_TYPE_CHOICES = [ ('Individual', 'مشتری حقیقی'), ('Corporate', 'مشتری حقوقی'), ] customer_type = models.CharField(max_length=20, choices=CUSTOMER_TYPE_CHOICES) class IndividualCustomer(models.Model): customer = models.OneToOneField(Customer, on_delete=models.CASCADE) # Other fields... class CorporateCustomer(models.Model): customer = models.OneToOneField(Customer, on_delete=models.CASCADE) # Other fields... # admin.py from django.contrib import admin from .models import Customer, IndividualCustomer, CorporateCustomer class IndividualCustomerInline(admin.StackedInline): model = IndividualCustomer extra = 0 class CorporateCustomerInline(admin.StackedInline): model = CorporateCustomer extra = 0 @admin.register(Customer) class CustomerAdmin(admin.ModelAdmin): inlines = [IndividualCustomerInline, CorporateCustomerInline] Custom Template (change_form.html): {% extends "admin/change_form.html" %} {% load i18n static %} {% block after_field_sets %} {{ block.super }} <style> .inline-group { margin-bottom: 20px; } </style> <script> document.addEventListener('DOMContentLoaded', function () { … -
Django Admin panel css not align
enter image description hereDjango admin CSS is not working as expected. As seen in the attached screenshot, the search box is misaligned. I need the search box to be properly aligned above the model data in the admin interface. Steps I've already tried: I have run collectstatic to make sure all static files are gathered. I cleared the cache to ensure no old files were affecting the layout. I verified that the custom CSS is correctly linked and applied, but the search box is still not aligning as needed. Details: Django version: 4.2.16 Issue: The search box appears out of alignment, and I want it to be positioned at the top, above the model data table. I would appreciate guidance on how to adjust the CSS or admin template to fix the alignment issue. -
Django Channels - Route not found
I have been grinding on this from past 4 days and still couldn't get the websockets connected , it always shows Not found : ws/play/testroomcode This is my consumers.py: from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class GameRoom(WebsocketConsumer): def connect(self,event): print('Websocket Received...',event) self.room_name = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = 'room_%s' % self.room_name print(self.room_group_name) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def receive(self,event): print('Websocket Received...',event) def disconnect(self,event): print('Websocket Disconnected...',event) game/asgi.py import osfrom django.core.asgi import get_asgi_applicationfrom channels.routingimport ProtocolTypeRouter, URLRouterfrom channels.auth import AuthMiddlewareStackfrom app1 import routing # Import your routingfrom app1.consumers import GameRoomfrom django.urls import path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'game.settings')websocket_urlpatterns = [path('ws/play/<room_code>', GameRoom.as_asgi()),] application = ProtocolTypeRouter({'http': get_asgi_application(),'websocket': AuthMiddlewareStack(URLRouter(websocket_urlpatterns)),}) game/settings.py INSTALLED_APPS = ['channels','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','app1', ] ASGI_APPLICATION = 'game.asgi.application' #WSGI_APPLICATION = 'game.wsgi.application' CHANNEL_LAYERS = {"default": {"BACKEND": "channels_redis.core.RedisChannelLayer","CONFIG": {"hosts": [("127.0.0.1", 6379)], # Use quotes around the IP address},},} I have tried following every YouTube tutorial nothing works for me, installed django, channel, channel-redis , virtual environment like every possible thing on internet but still got no where on how to connect it. Read all the solutions on Stack overflow that have similar errors like mine but none of them works for me. -
Can you set permission classes per function in class-based views?
Let's say we have the following class-based view (CBV) implementing DRF's APIView: class ExampleListAPIView(APIView): permission_classes = [IsAuthenticatedOrReadOnly] def get(self, request): ''' List all examples ''' examples = Example.objects.all() serializer = ExampleListSerializer(examples, many=True) return Response(serializer.data, status.HTTP_200_OK) def post(self, request): ''' Create new example ''' serializer = ExampleListSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Using permission_classes to set authentication policy in CBV, the policy is applied to all methods of class. Is it possible to set permission per function in a CBV, e.g. class ExampleListAPIView(APIView): def get(self, request): # Apply [AllowAny] # logic def post(self, request): # Apply [IsAuthenticated] # logic Or you have to use function-based views to achieve this behavior? -
Python Django sees old migrations but everything was deleted
I cleared all my database, even created new with different name, deleted all migrations and migrations folder in every app of my django project, cleared all images, containers, volumes and builds in my Docker. But when I am running python manage.py showmigrations it shows me my old migrations, but I have no idea where does it finds them, because I deleted everything I could. and when I am running python manage.py makemigrations it returns me message "No changes detected" I even changed database name to new one. I deleted everything and just wanted to start from zero, but somehow it finds old migrations that doesn't even exist. enter image description here -
Can I make a dj-rest-auth login screen that uses a different database for login details?
I want to make a login screen for my Django Rest framework. I want to create a login page that's based on my database and not the default credentials of dj-rest-auth. Is it possible to do? Or should I use something else? I looked for solutions to this and only found ways to customize my the login details with the default django auth database. -
Django Rest Framework - Cross Origin Resquest got blocked
I'm developing an API using Django Rest Framework. I'm trying to list or create an "Article" object, but when i'm trying to access the console gives me this error: I host my frontend at http://localhost:3000 and sending request to 127.0.0.1:8000 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/articles/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. With this in setting.py, I got the above error CORS_ALLOWED_ORIGINs = [ "http://localhost:3000", ] but if using this code then it runs smoothly CORS_ORIGIN_ALLOW_ALL = True This is my GET request useEffect(() => { fetch("http://127.0.0.1:8000/api/articles/", { 'method': "GET", headers: { 'Content-Type': 'application/json', 'Authorization': 'Token 746a97c3f72a5fc388762c5732e2c8340fc75ba9', } }) .then(res => res.json()) .then((data) => setArticles(data)) .catch((error) => console.log(error)) }, []); Other configurations in setting.py seem to be set up correctly. -
Stream an entire folder using Django without reading everything to memory
The premise is similar to this question. But the accepted answer not only requires every file to be in memory to work. The answer does provide an example of iterator usage but that doesn't work with open(file, 'rb').read(chunk_size). More importantly that solution doesn't actually download folder. It only group multiple files togather. -
with Django , When I use connection pool , eoor(PoolTimeout) occurs. why?
When I use connection pool, yhere is no problem when starting it for the first time run, but, After a while, an error will start occurring. Traceback (most recent call last): File "web/django/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 279, in ensure_connection self.connect() File "web/django/venv/lib/python3.11/site-packages/sentry_sdk/utils.py", line 1786, in runner return sentry_patched_function(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/sentry_sdk/integrations/django/__init__.py", line 692, in connect return real_connect(self) ^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 348, in get_new_connection connection = self.pool.getconn() ^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/psycopg_pool/pool.py", line 202, in getconn raise PoolTimeout( psycopg_pool.PoolTimeout: couldn't get a connection after 30.00 sec The above exception was the direct cause of the following exception: Traceback (most recent call last): File "repli/web/django/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/sentry_sdk/integrations/django/views.py", line 90, in sentry_wrapped_callback return callback(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/user/.pyenv/versions/3.11.2/lib/python3.11/contextlib.py", line 80, in inner with self._recreate_cm(): File "web/django/venv/lib/python3.11/site-packages/django/db/transaction.py", line 198, in __enter__ if not connection.get_autocommit(): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 454, in get_autocommit self.ensure_connection() File "web/django/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line … -
Django Testing in PyCharm. manage
I have a simple django project that I'm making in pycharm. The directory structure is the following: zelda_botw_cooking_simulator |-- cooking_simulator_project |---- manage.py |---- botw_cooking_simulator # django app |------ init.py |------ logic.py |------ tests.py |------ all_ingredients.py |------ other standard django app files |---- cooking_simulator_project # django project When I run python manage.py test in the PyCharm terminal, everything works great. When I click the little triangle icon in PyCharm next to a test to run that test, however, I get an error saying: File ".../zelda_botw_cooking_simulator/cooking_simulator_proj/botw_cooking_simulator/tests.py", line 5, in <module> from .all_ingredients import all_ingredients ImportError: attempted relative import with no known parent package How can I fix this? I have tried configuring run environments and test environments in PyCharm for 30 minutes now and I'm not getting it. The questions/answers here and here are close, but there's not quite enough detail for me to fix it. Exactly what do I put in each field in each window? What's the 'target', the 'working directory', do I need an environment variable? What goes in the settings part and what goes in the configuration? ChatGPT recommended a bunch of stuff that didn't work. Thank you! -
Under what circumstances will django's bulk_update generate case when?
When running the following program, I found that case when SQL was finally executed. In which part of the Django source code is this processing logic implemented? How to optimize it? Thanks Django ORM AccountInfo.objects.bulk_update(update_list, ['account_name', 'account_status', 'account_type']) executed SQL UPDATE account_info SET account_name = CASE WHEN (account_info.id = 814245) THEN 'Beeeesos' WHEN (account_info.id = 814248) THEN 'Apple223' ... -
Django SelectDateWidget default values for month and year only
I use the SelectDateWidget in my form and want to give default values for year and month, but show the empty_label (----) on day. I either get all three fields to be empty_label, or all fields showing the default date (timezone.now()). -
How to edit lines of bar chart in apache superset based on threshold
***I am unable to customise colour of bar char in Apache super-set dashboard. The goal is if count/sum/avg is greater then 100 the colour should be blue of the line, elif greate then 1200 the colour should be red of the line and so on. I have tried to alter yaml files but failed. Here is my yaml file. I am currently trying to modify vaccine dashboard bar chart (vaccine candidate per phase). The colour for count should be dynamic. Any suggestion? What should be yaml file, SQL query? or any changes needed in react components???*** .... description: '' chartsInScope: - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 66 tabsInScope: - TAB-BCIJF4NvgQ id: NATIVE_FILTER-EWNH3M70z controlValues: enableEmptyFilter: false defaultToFirstItem: false multiSelect: true searchAllOptions: false inverseSelection: false name: Clinical Stage filterType: filter_select targets: column: name: clinical_stage datasetUuid: 974b7a1c-22ea-49cb-9214-97b7dbd511e0 defaultDataMask: extraFormData: {} filterState: {} ownState: {} cascadeParentIds: [] scope: rootPath: ROOT_ID excluded: [] type: NATIVE_FILTER description: '' chartsInScope: 9 10 11 12 13 14 15 66 tabsInScope: TAB-BCIJF4NvgQ color_scheme: supersetColors label_colors: "0": "#D3B3DA" "1": "#9EE5E5" Pre-clinical: "#1FA8C9" Phase II or Combined I/II: "#454E7C" Phase I: "#5AC189" Phase III: "#FF7F44" Authorized: "#666666" root: "#1FA8C9" Protein subunit: "#454E7C" … -
Django storages + boto3 not working. Keeping static files local while uploading media files to S3
I'm trying to setup a django project in such a way that static files are kept in the filesystem and media files are uploaded to an amazon s3 bucket. The django storages library had an update for django>4.2. This used to be easy, now, its not working with the new settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'django.core.files.storage.FileSystemStorage' # Check if running in a production environment STORAGES = { 'default': { 'BACKEND': 'storages.backends.s3boto3.S3Boto3Storage', 'OPTIONS': { 'bucket_name': os.getenv('AWS_STORAGE_BUCKET_NAME'), 'region_name': os.getenv('AWS_S3_REGION_NAME', 'us-east-1'), 'default_acl': 'public-read', 'file_overwrite': False, 'custom_domain': f'{os.getenv("AWS_STORAGE_BUCKET_NAME")}.s3.{os.getenv("AWS_S3_REGION_NAME", "us-east-1")}.amazonaws.com', }, }, 'staticfiles': { 'BACKEND': 'django.core.files.storage.FileSystemStorage', 'OPTIONS': { 'location': STATIC_ROOT, }, } } # django-storages configuration for media files DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = f'https://{os.getenv("AWS_STORAGE_BUCKET_NAME")}.s3.{os.getenv("AWS_S3_REGION_NAME", "us-east-1")}.amazonaws.com/media/' When accessing the site from the server, the static files still point to the s3 bucket, for example: us-east-1.amazonaws.com/media/admin/css/dark_mode.css That is the basic css for the django admin. But why is it looking for the file in /media/? -
TypeError: ForwardRef._evaluate() missing 1 required keyword-only argument: 'recursive_guard' on Mac
I was developing my fastapi project in my windows PC and everything was working fine there, but I recently got a new macbook and installed the lastest python 3.13 version and everything is just giving error When I try to run my fastapi server, its giving this error :- (venv) venvlisa@Lisas-MacBook-Air src % uvicorn main:app --host 0.0.0.0 --port 8000 --reload INFO: Will watch for changes in these directories: ['/Users/lisa/Documents/Projects/phia-backend-python/src'] INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) INFO: Started reloader process [67473] using WatchFiles Process SpawnProcess-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/process.py", line 313, in _bootstrap self.run() ~~~~~~~~^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/_subprocess.py", line 76, in subprocess_started target(sockets=sockets) ~~~~~~^^^^^^^^^^^^^^^^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/server.py", line 61, in run return asyncio.run(self.serve(sockets=sockets)) ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/asyncio/runners.py", line 194, in run return runner.run(main) ~~~~~~~~~~^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/asyncio/runners.py", line 118, in run return self._loop.run_until_complete(task) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/asyncio/base_events.py", line 721, in run_until_complete return future.result() ~~~~~~~~~~~~~^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/server.py", line 68, in serve config.load() ~~~~~~~~~~~^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/config.py", line 473, in load self.loaded_app = import_from_string(self.app) ~~~~~~~~~~~~~~~~~~^^^^^^^^^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/importer.py", line 21, in import_from_string module = importlib.import_module(module_str) File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/importlib/__init__.py", line 88, in import_module return _bootstrap._gcd_import(name[level:], package, level) ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen … -
Dokku Procfile "release: python manage.py migrate" results in a NodeNotFoundError "Migration XYZ dependencies reference nonexistent parent node"
When i push to the dokku test environment, i get the following error when the Procfile is being used: -----> Releasing aha-website-test... -----> Checking for predeploy task No predeploy task found, skipping -----> Checking for release task Executing release task from Procfile in ephemeral container: python manage.py migrate =====> Start of aha-website-test release task (825335cfe) output remote: ! Traceback (most recent call last): remote: ! File "/app/manage.py", line 10, in <module> remote: ! execute_from_command_line(sys.argv) remote: ! ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line remote: ! utility.execute() remote: ! ~~~~~~~~~~~~~~~^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/__init__.py", line 436, in execute remote: ! self.fetch_command(subcommand).run_from_argv(self.argv) remote: ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/base.py", line 413, in run_from_argv remote: ! self.execute(*args, **cmd_options) remote: ! ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/base.py", line 459, in execute remote: ! output = self.handle(*args, **options) remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/base.py", line 107, in wrapper remote: ! res = handle_func(*args, **kwargs) remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/commands/migrate.py", line 118, in handle remote: ! executor = MigrationExecutor(connection, self.migration_progress_callback) remote: ! File "/usr/local/lib/python3.13/site-packages/django/db/migrations/executor.py", line 18, in __init__ remote: ! self.loader = MigrationLoader(self.connection) remote: ! ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/db/migrations/loader.py", line 58, in __init__ remote: ! self.build_graph() remote: ! ~~~~~~~~~~~~~~~~^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/db/migrations/loader.py", line 276, in build_graph …