Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make function, after specific time/minute the status of post change status using django?
i want to create a function in views or html file after 15 seconds , the status of post from pending to activa using django? tried to look for solutions but didnt understand. Also looked to ai to see what type of answer gave , but wanted to use traditional help to understand better -
How to run react code to render a webpage and display to user?
Say I have some generated react code that I want to display to the user for them to click through and comment on. The user isn't the one coding the website, I just want to show them how the generated website looks so they can make some comments on it. An example of the generated code could look like this: import { useState } from 'react'; import { Card, CardHeader, CardContent } from '@/components/ui/card'; import { MailIcon, GithubIcon, LinkedinIcon } from 'lucide-react'; export default function Website() { const [activeTab, setActiveTab] = useState('about'); return ( <div className="min-h-screen bg-gray-100 p-8"> {/* Navigation */} <nav className="bg-white shadow-lg rounded-lg p-4 mb-8"> <div className="flex justify-between items-center"> <h1 className="text-2xl font-bold text-blue-600">My Website</h1> <div className="space-x-4"> <button onClick={() => setActiveTab('about')} className={`px-4 py-2 rounded ${activeTab === 'about' ? 'bg-blue-600 text-white' : 'text-gray-600'}`} > About </button> <button onClick={() => setActiveTab('projects')} className={`px-4 py-2 rounded ${activeTab === 'projects' ? 'bg-blue-600 text-white' : 'text-gray-600'}`} > Projects </button> <button onClick={() => setActiveTab('contact')} className={`px-4 py-2 rounded ${activeTab === 'contact' ? 'bg-blue-600 text-white' : 'text-gray-600'}`} > Contact </button> </div> </div> </nav> {/* Main Content */} <div className="max-w-4xl mx-auto"> {activeTab === 'about' && ( <Card> <CardHeader> <h2 className="text-2xl font-bold">About Me</h2> </CardHeader> <CardContent> <p className="text-gray-600"> Hello! I'm a … -
How to skip django DeleteModel operation
I have deleted a model, Django creates a DeleteModel operation that I'd like to skip because i don't want to drop the table yet, but i also don't want to keep the model around. How can i skip dropping the table in this case but still delete the model? I have tried commenting out the operation in the migration file but the next time you run makemigrations command the operation is recreated. -
Handling Errors in Django Test Cases
I am currently writing test cases using Django and would like to improve the way we handle errors, particularly distinguishing between errors that arise from the test cases themselves and those caused by the user's code. Context: Let’s say a user writes a function to fetch and increment the likes count of a post: def fetch_post(request, post_id): try: post = Post.objects.get(id=post_id) except Post.DoesNotExist: raise Http404("Post not found") post.likes += 1 post.save() return HttpResponse("Post liked") Here’s the test case for that function: from django.test import TestCase from project_app.models import Post from django.urls import reverse from django.http import Http404 class FetchPostViewTests(TestCase): def setUp(self): self.post = Post.objects.create(title="Sample Post") def assertLikesIncrementedByOne(self, initial_likes, updated_post): if updated_post.likes != initial_likes + 1: raise AssertionError(f'Error: "Likes cannot be incremented by {updated_post.likes - initial_likes}"') def test_fetch_post_increments_likes(self): initial_likes = self.post.likes response = self.client.get(reverse('fetch_post', args=[self.post.id])) updated_post = Post.objects.get(id=self.post.id) self.assertLikesIncrementedByOne(initial_likes, updated_post) self.assertEqual(response.content.decode(), "Post liked") def test_fetch_post_not_found(self): response = self.client.get(reverse('fetch_post', args=[9999])) self.assertEqual(response.status_code, 404) Scenario: Now, if a user accidentally modifies the code to increment the likes by 2 instead of 1 and didn't save the post object. # Wrong code that will fail the test case def fetch_post(request, post_id): try: # used filter() method instead of get() method post = Post.objects.filter(id=post_id) except Post.DoesNotExist: … -
AxesBackend requires a request as an argument to authenticate
I need to add a restriction on account login attempts to my django site, I found the popular django-axes library, followed the documentation and code examples, but when I try to log in to my account (whether the password is correct or not) I get the error AxesBackend requires a request as an argument to authenticate even though my code follows the instructions exactly and I'm passing the request. Here is all the code that is somehow related to this: settings.py INSTALLED_APPS = [ ... 'axes', ] MIDDLEWARE = [ ... 'axes.middleware.AxesMiddleware', ] AXES_FAILURE_LIMIT = 4 AXES_RESET_ON_SUCCESS = True AXES_COOLOFF_TIME = 1 AUTHENTICATION_BACKENDS = [ 'axes.backends.AxesBackend', # Axes must be first 'django.contrib.auth.backends.ModelBackend', ] AUTH_USER_MODEL = "users.User" LOGIN_URL = "/user/login/" views.py from django.contrib import auth, messages def login(request): if request.method == "POST": form = UserLoginForm(data=request.POST) if form.is_valid(): username = request.POST["username"] password = request.POST["password"] user = auth.authenticate(request=request, username=username, password=password) if user: auth.login(request, user) redirect_page = request.POST.get("next", None) if redirect_page and redirect_page != reverse("user:logout"): return HttpResponseRedirect(request.POST.get("next")) return HttpResponseRedirect(reverse("main:main_page")) else: form = UserLoginForm() context = {"title": "Вход", "form": form} return render(request, "users/login.html", context) Django==5.0.4 django-axes==6.5.2 I would be very grateful for your help! Indicated above. Here is the exact output in the console that … -
error: PermissionError(13, 'Access is denied', None, 5, None)
I have this error while working with celery [2024-10-06 14:38:15,464: ERROR/SpawnPoolWorker-3] Pool process <billiard.pool.Worker object at 0x0000016C0BBF5A00> error: PermissionError(13, 'Access is denied', None, 5, None) Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 473, in receive ready, req = _receive(1.0) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 445, in _recv return True, loads(get_payload()) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\queues.py", line 394, in get_payload with self._rlock: File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\synchronize.py", line 115, in __enter__ return self._semlock.__enter__() ^^^^^^^^^^^^^^^^^^^^^^^^^ PermissionError: [WinError 5] Access is denied During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 351, in workloop req = wait_for_job() ^^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 480, in receive raise SystemExit(EX_FAILURE) SystemExit: 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 292, in __call__ sys.exit(self.workloop(pid=pid)) ^^^^^^^^^^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 396, in workloop self._ensure_messages_consumed(completed=completed) File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 406, in _ensure_messages_consumed if self.on_ready_counter.value >= completed: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<string>", line 3, in getvalue PermissionError: [WinError 5] Access is denied [2024-10-06 14:38:15,464: ERROR/SpawnPoolWorker-3] Pool process <billiard.pool.Worker object at 0x0000016C0BBF5A00> error: PermissionError(13, 'Access is denied', None, 5, None) Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 473, in receive ready, req = _receive(1.0) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 445, in _recv return … -
How are emails set up for employees in an organization?
I'm pretty new to the SMTP aspect... I have been trying to understand how setting up an email account for each user (employee) in an enterprise application works. For example, let's say I am using Brevo (SendinBlue) as my SMTP service and I want to create for each lecturer that I have in my application, say john.smith@havard.org Do I create another sender on Brevo for each of the accounts I want to create and would the user be able to login to his email and view emails sent to him? And I would be able to send a dynamic email from my backend using from his email Just, how does it work? -
CommandError: Unknown command:
I created a custom command and want to run it automatically on start My command file # project/parser_app/management/commands/create_schedules.py class Command(loaddata.Command): def handle(self, *args, **options): # some code Added command to wsgi.py import os from django.core.wsgi import get_wsgi_application from django.core.management import call_command os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') application = get_wsgi_application() call_command("makemigrations") call_command("migrate") call_command("collectstatic", interactive=False) call_command("create_schedules parser_app/management/commands/schedule_fixtures.json") I can run in console command python manage.py "create_schedules parser_app/management/commands/schedule_fixtures.json" and everything is working but when I added command to wsgi.py (to run on start) import os from django.core.wsgi import get_wsgi_application from django.core.management import call_command os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') application = get_wsgi_application() call_command("makemigrations") call_command("migrate") call_command("collectstatic", interactive=False) call_command("create_schedules parser_app/management/commands/schedule_fixtures.json") I have an error raise CommandError("Unknown command: %r" % command_name) django_1 | django.core.management.base.CommandError: Unknown command: 'create_schedules parser_app/management/commands/schedule_fixtures.json' -
In Django, how to retrieve an id to use in a dynamic link?
I have a Django app. In my sidebar I have a navigation link that goes to a list of reports. That link needs an id to get the correct list of reports. The <li> element in base.html that links to the ga_reports page is below. This link needs the app_config.id to resolve correctly. With this element {{ app_config.id }} does not exist because {{ app_config }} does not exist. I will add that on the Reports page, this link works as {{ app_config }} gets created. Why does {{ app_config }} exist on the Reports page but not on the parent page? <li class="relative px-12 py-3"> <a class="inline-flex items-center w-full text-sm font-semibold transition-colors duration-150 hover:text-gray-800 dark:hover:text-gray-200 " href="/base/ga_reports/{{ app_config.id }}"> <span class="ml-4">Reports</span> </a> </li> These are entries from base/urls.py path('app_config', app_config_views.app_config, name='app_config'), ... path('ga_reports/<int:app_config_id>', ga_views.ga_reports, name='ga_reports'), The AppConfiguration model is included on base/views.py from .models import AppConfiguration This is base/ga_views.py @login_required def ga_reports(request, app_config_id): app_config = AppConfiguration.objects.filter(id = app_config_id).first() if not app_config: messages.error(request, "Invalid Configuration") return redirect('app_config') return render(request, 'base/ga_reports.html', {'app_config': app_config}) This is app_config_views.py. @login_required def app_config(request): app_configs = [] for app_type in APP_TYPE: app_type_subscription = UserSubscription.objects.filter(user_id = request.user.id, app_type = app_type[0], is_active = True, is_expired = False).first() app_configuration … -
What is the best way to sanitize uploaded filenames in Django?
I tried using slugify however it made too many changes to the original filename, such as removing spaces joining the file extension to the rest of the name. I'd like to simply ensure that names are safe: 1. Not too long and 2. Prevent any attacks that can be carried out using the file's name(such as path traversal). My app allows users to upload files(files are uploaded to DigitalOcean Spaces via my app) and filenames are stored using models.py/ -
How to get the estimated remaining time of an already started Celery task?
I am using django with Celery and redis. I would like that when a user initiates a Celery task my app estimates the amount of time left until the task is completed(so that I can, for example, represent this data to the frontend as a progress bar). For example, given this polling function: views.py: @csrf_protect def initiate_task(request): task = new_celery_task.delay(parmeter_1, parametr_2) @csrf_protect def poll_task_status(request, task_id): #task_id provided by frontend import base64 task_result = AsyncResult(task_id) if task_result.ready(): try: ... response_data = { 'status': 'completed', } except Task.DoesNotExist: return JsonResponse({'status': 'error', 'message': 'There has been an error'}, status=404) elif task_result.state == 'REVOKED': return JsonResponse({'status': 'terminated', 'message': 'Task was terminated'}) else: #add code to calculate estimated remaining time here remaining_time_est = estimate_remaining_time() #estimate task by id return JsonResponse({'status': 'pending' #add code to return estimated remaining time here 'est_remaining_time':remaining_time_est }) and task: task.py: app = Celery('myapp')# @app.task def new_celery_task(arg_1, arg_2): #complete task How would I estimate the remaining time left on an initiated task? -
My django project shows no error in terminal using vs code it got right request but on browser it not showing what i expected the output, not updated
I am facing some problem in VS code in django project. After saving the code in vs code, even after running the server in the terminal, I am not getting the output of the code in the browser normally. pylance - does not show any errors. The update of get request in terminal comes every time after running server but still doesn't show data in browser. Despite not giving pylance error, I check the code 5-6 times by myself. There is no error. I have not installed pylint as I am still in medium level pylint asks to follow the actual code structure of pep8 which is a bit tough now so I did not install it, still why is this happening. Tried a simple project for 2 hours yesterday and couldn't figure out the error, I was sure the code was fine. Running the same project this morning, everything is running fine. I am reading the same problem again today. Even after browser reload/hard reload, browser change, even port number change, the same problem is happening again and again. I want a solution, can someone tell me where the problem is? Point to be noted, the terminal shows no … -
Best approach for showing custom data in the Volt template dashboard for Django
I am currently building a personal app and would like to use the Volt template for Django. The link to the template is here: https://tb-volt-dashboard-django.appseed-srv1.com/dashboard.html I want to update the chart in the dashboard to use custom generated data from the view. What's the best approach/ recommended approach to do that? I see currently that the data is being hard-coded in the volt.js file in the Volt directories. -
How to Separate Django Channels WebSockets into a Scalable Microservice for a Multiplayer Game?
I have a Django web application that includes a multiplayer game feature, using Django Channels for real-time communication over WebSockets. Currently, the WebSockets functionality (real-time game updates, player interactions, etc.) is handled directly within the main Django application. As the project grows, I'm considering separating the WebSockets/game logic into its own microservice for scalability and maintainability. My goals are to have a dedicated microservice that handles all real-time communication and game logic, and to be able to scale this service independently of the main Django web app. Here are the specific details of my setup: Backend Framework: Django (with Django Channels for WebSockets) Current Architecture: Monolithic Django app with WebSockets handled directly in the same codebase - as the rest of the application Desired Architecture: Separate microservice dedicated to handling WebSocket connections and game logic, which can be scaled independently Questions: What are the best practices for separating WebSocket real-time communication into a dedicated microservice? What tools or technologies can be useful for building this scalable WebSocket-based microservice? I'd like not to use another django services but something lighter How should communication between the main Django app and the WebSocket microservice be handled (e.g., API, message queues, etc.)? How should … -
Django (DRF): How can I apply authentication on this class-based view?
In my Django project I have two User Groups: Manager Employee Now I'm trying to build a class-based view that returns all managers. However, it's only supposed to be accessible to managers. If an employee or an anonymous user attempts to access it, it's supposed to return a 403-HTTP-Status code. I've built the class-based view so far and for simplicity it extends generics.ListAPIView. But I can't find a way to apply the desired authentication. I have removed the "Can view group" and "Can view user" permissions from the Employee group, so no employee can view the managers. I've tried several permission_classes, but everytime I sent a GET-request containing an employee's token via Insomnia, it returned the managers instead of a 403-Status code. Help is greatly appreciated. Here's the code of the view: class ViewManager(generics.ListAPIView): permission_classes = [DjangoModelPermissions] group = Group.objects.get(name='Manager') users = group.user_set.all() queryset = users serializer_class = ManagerSerializer -
Celery polling Redis every second
I have a Django application with two celery tasks set up. Both the tasks need to run only once at one minute after midnight (12:01 AM). This is just to update some statuses which change from "ACTIVE" to "INACTIVE" at 12:01 AM. My goal is to reduce the number of times Celery polls Redis. Currently, it polls every second which is problematic. I took two steps I tried to change the settings in Django for Celery inlcuding using paramters such as CELERY_IGNORE_RESULT, CELERY_WORKER_CONCURRENCY, CELERY_BROKER_HEARTBEAT and lastly CELERY_BEAT_MAX_LOOP_INTERVAL CELERY_RESULT_BACKEND = None CELERY_IGNORE_RESULT = True # Ignore task results to reduce Redis usage CELERY_ACCEPT_CONTENT = ["json"] CELERY_TASK_SERIALIZER = "json" CELERYD_PREFETCH_MULTIPLIER = 1 # Fetch only 1 task at a time CELERY_ACKS_LATE = True # Acknowledge tasks after completion to avoid re-execution on failure # Celery transport options CELERY_BROKER_TRANSPORT_OPTIONS = { 'ssl': { 'ssl_cert_reqs': ssl.CERT_NONE # Suggestion: CERT_REQUIRED for stronger security }, 'visibility_timeout': 3600, # Timeout for long-running tasks 'polling_interval': 30 # Poll every 30 seconds } CELERY_RESULT_BACKEND_TRANSPORT_OPTIONS = { 'ssl': { 'ssl_cert_reqs': ssl.CERT_NONE # Same as broker for consistency } } # Reduce the number of threads/processes CELERY_WORKER_CONCURRENCY = 1 # Disable sending task events CELERY_WORKER_SEND_TASK_EVENTS = False # Disable remote control … -
In my browser console window.crossOriginIsolated is false despite of adding all proper COOP COEP CORP headers in my React Js and Django app
when i access cmd to express-> node server.js with coop and coep and corp headers and access directly the locahost:8080/ everything is working fine and even window.crossOriginIsolated is true. but when i integrate it to my existing react js and django and i add custom middleware.py for coop and coep. but still no use... even the pages of any of my reactjs and django itself is not showing window.crossOriginIsolated true despite of adding all required headers. kindly help me. i dont have any cors error at all my app works fine with api's transaction between react js and django working fine. this is custom middleware for cors `from django.http import HttpResponse class CrossOriginIsolationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Handle OPTIONS preflight request (for CORS) if request.method == 'OPTIONS': response = HttpResponse() response['Access-Control-Allow-Origin'] = 'http://localhost:3000' # Specify the frontend origin response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE' return response response = self.get_response(request) response['Access-Control-Allow-Origin'] = 'http://localhost:3000' response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE' if request.path.startswith('/dicomweb/'): response['Cross-Origin-Opener-Policy'] = 'same-origin' response['Cross-Origin-Embedder-Policy'] = 'require-corp' response['Cross-Origin-Resource-Policy'] = 'cross-origin' # Changed to … -
Django forms.py and Join.html not rendering form errors
I have seen many tutorials on this, (I am new to Django) and the only issue I could find was raise form.Validation("...") was not rendering on my HTML template and did not stop the form from submitting. I tried many options including AI yet I was still running into the same problems. If I have made a silly mistake please point it out so I know for next time, this code is just a project of mine so I can learn how to code Django. HTML: <form id="form" action="" method="post" name="form"> {% csrf_token %} <div class="input-control"> {% if form.non_field_errors %} <div class="error">{{ form.non_field_errors }}</div> {% endif %} {% if form.errors %} <div class="error">{{ form.errors }}</div> {% endif %} <div class="username"> <label for="{{ form.username.id_for_label }}" class="label">{{ form.username.label }}</label> {{ form.username }} <!-- Render the input field --> {% for error in form.username.errors %} <div class="error">{{ error }}</div> {% endfor %} </div> <div class="email"> <label for="{{ form.email.id_for_label }}" class="lemail">{{ form.email.label }}</label> {{ form.email }} {% for error in form.email.errors %} <div class="error">{{ error }}</div> {% endfor %} </div> <div class="password"> <label for="{{ form.password.id_for_label }}" class="label">{{ form.password.label }}</label> {{ form.password }} {% for error in form.password.errors %} <div class="error">{{ error }}</div> {% endfor … -
How Can I Setup Celery in my Flask Project (Beginner)
So I've been working on a project for a couple months now and I've been trying to implement Celery into my flask project and it has not gone well. I thought maybe it's my computer or windows or something like, and all the responses I've seen are from a couple years ago and I don't think that they would still work because those were the ones I tried using. So thank you for any responses in advance. I tried using the celery config from the documentation and some chat gpt tutorials but they haven't been of help. And I'm running redis as the broker and result backend on the localhost -
UnicodeDecodeError: 'UTF-8' codec can't decode byte 0xff in position 0: invalid start byte. DRF
There is a backend on django and a postgres DB that stores data about the item, including pictures. And there is a problem with getting a picture from the database, i've looked at enough solutions, but none of them work. serializers.py import base64 import uuid import imghdr class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): if isinstance(data, str) and 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except (TypeError, ValueError): self.fail('invalid_image') file_name = str(uuid.uuid4())[:12] file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = f"{file_name}.{file_extension}" data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): extension = imghdr.what(file_name, decoded_file) return extension or 'jpg' class CreateItemSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') photo = Base64ImageField(required=True) class Meta: model = CreateItem fields = '__all__' def create(self, validated_data): items = CreateItem.object.create_item( name = validated_data.get('name'), price = validated_data.get('price'), description = validated_data.get('description'), type_item = validated_data.get('type_item'), photo=validated_data.get('photo') ) return items views.py class GetItemView(APIView): serializer_class = CreateItemSerializer def get(self, request): items = CreateItem.object.all() response_data = { 'items': [ { 'photo': item.photo, 'name': item.name, 'description': item.description, 'type_item': item.type_item, 'price': item.price, } for item in items ] } return Response(response_data, status=status.HTTP_200_OK) full error traceback Internal Server Error: /api/v1/item/items-get/ Traceback (most recent call last): File "/home/anton/Documents/e-m/e-market/backend/my_backend/venv_em/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = … -
Using React in existing Django Project
I have an existing Django project. Its a website that displays a map with leaflet. Markers and everything is loaded dynamically from django. Now I want to enhance that with React. In a sense that when you click a marker on the map, react will render based on marker_id the specific marker-details in a sidebar or something. I am not sure how to do that. In the django template I have a onclick event to get the marker-details: marker.uri = `/map/api/marker_details/?marker_id=${marker.marker_id}&marker_type=${marker.marker_type}` marker.on('click', function (e) { jQuery.get(this.uri); }); Since this is all in django template and not in React, the result is probably not accessible via react to render the details. Do I have to implement the map with the marker and everything in React to then be able to render the details via API? What am I missing? -
Graphql Apollo client
I want to send some data to my graphql python django that stores the data to mysql database. The data are week of planting, the block planted and images,videos. Using react as fronted, I have used dropzone in my react. But it just sending empty objects for image and video fields Sending and storing images to mysql db⁷ -
Iframe of the main page without authorization for an authorized user
Django. There was a problem while creating the website page. A user who is registered and authorized on the site should see the main page in an iframe, but as an unregistered user. Is this possible? -
Django /media/ files not served in production on hosting
I really feel like i am stuck, and hosting support doesn't include configuration help so maybe someone here would know i have django server with model: class Video(models.Model): thumbnail = models.ImageField(upload_to='thumbnails/', blank=True, null=True) saved here in folder thumbnails: MEDIA_URL = '/media/' MEDIA_ROOT = '/home/username/domains/domain.com/djangoapp/media' when i later want to use uploaded image in html: <img src="{{ video.thumbnail.url }}" alt="{{ video.title }}" class="video-thumbnail"> it it not served in production (works on debug=True), file not found 404 File is correctly uploaded, but not served I did python3 manage.py collectstatic enter image description here with no result Here's .htaccess file in the domain folder: enter image description here # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/username/domains/domain.com/djangoapp" PassengerBaseURI "/" PassengerPython "/home/username/virtualenv/domains/domain.com/djangoapp/3.7/bin/python" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_URI} ^/media/ RewriteRule ^media/(.*)$ /home/username/domains/domain.com/djangoapp/media/$1 [L] </IfModule> that i tried adding this rule to, with no result. Any ideas on what could i try? Or anybody who had simillar problem? I tried to clear database and migrate it from zero. Tried collecting static. I tried changing rule in .htaccess. I tried running in debug and it worked. -
Mixing gzip & brotli in Django
I have django-brotli installed and use it's middleware. I would like Django to also serve gzipped content in case the client doesn't support brotli. Is it as easy as just adding GZipMiddleware to the middlewares list? I don't want them to potentially mix with eachother.