Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter queryset from filename field based on two words that appear one after the other Django
I have a Files table, which contains various fields, one of which is a filename. Within each one of the files in this table, there is a specific file that I'd like to retrieve, which is basically a terms and conditions. This filename will always have the words 'terms' and 'conditions' within the filename itself, and it will always be in that order. However, there could be other words surrounding both 'terms' and 'conditions'. For example, a filename could be 'my new terms and conditions' or 'my even better terms blah blah conditions'. I'm trying to write a queryset that will retrieve such a file using Regex but I'm not able to do so. So far, I have something like: file = Files.objects.filter( Q(filename__iregex=r'(^|\W){}.*({}|$)'.format("term", "condition")) ).first() but this doesn't work. -
pytest-django cannot find my existing module
to give a bit of context, I'm learning test unit in django and made an overly simple app to get started (Attach is the structure of my project). Here is my problem: When launching my unit tests on my django app, I get a ModuleNotFoundError event though the module exists. Sample of code: from django.shortcuts import get_object_or_404, render from .models import Book def book_infos(request, pk): book = get_object_or_404(Book, pk=pk) return render(request, "book_infos.html", {'book': book}) And the test associated: import pytest from django.urls import reverse from django.test import Client from django_pytest.library.models import Book from pytest_django.asserts import assertTemplateUsed @pytest.mark.django_db def test_book_infos_view(): client = Client() Book.objects.create(author="Jules Verne", title="20 milles lieues sous les mers") path = reverse('infos', kwargs={'pk': 1}) response = client.get(path) content = response.content.decode() expected_content = "<p>Jules Verne | 20 milles lieues sous les mers</p>" assert content == expected_content assert response.status_code == 200 assertTemplateUsed(response, "book_infos.html") My pytest.ini is as follow [pytest] pythonpath = . library tests DJANGO_SETTINGS_MODULE = django_pytest.settings python_files = test_*.py When I run pytest tests/library/test_views.py from django-pytest I get this result: platform win32 -- Python 3.11.5, pytest-7.4.3, pluggy-1.3.0 django: version: 4.2.7, settings: django_pytest.settings (from ini) rootdir: ...\django-pytest\django_pytest configfile: pytest.ini plugins: django-4.6.0 _ ERROR collecting tests/library/test_views.py _ ImportError while importing test module … -
Communication between AWS App Runner & EC2 instance
I've read about this subject in a couple of questions, but I haven't found the solution yet. So, I'm reasking almost the same question, as many others have done before: I have a Django app deployed on an App Runner server, and I have a backend process (in Python too) deployed on an EC2 instance. I need to be able to communicate values between this two servers, so when the user interacts with the django app, this calls the EC2 backend, processes the info and returns an output. Currently, I'm trying this like so: On my Django app I have this code. On button click it executes the ecconsult(): from django.shortcuts import render, HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json import requests def home(request): return render(request, 'index.html') def ecconsult(request): data_to_send = "communication test" response = requests.post('http://specific_host:specific_port/api/procesar', json=data_to_send) if response.status_code == 200: jsondatabe = response.text response_data = {'jsondatabe': jsondatabe} else: print('Error al procesar la call del backend') return render(request, 'index.html', response_data) And on my EC2 BackEnd server, I recieve the data like so: from flask import Flask, request, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app, resources={r"/api/*": {"origins": "Django_app_domain"}}) @app.route('/') def hello(): print("accesing from outside") return … -
Trouble with Docker and Colima: Django Container Not Reflecting Code Changes Until Docker Restart
I'm using colima version 0.5.6 to run Docker. I have three containers: Django, .... I'm encountering a problem with the Django container.When I edit the code and save it, no changes appear on the interface, even after refreshing the page. The only way to see the changes is by executing the following command: docker restart django. the same config works. with docker descktop. i checked the yaml file and it already contains this line :restart: unless-stopped in the container config: services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: local_django container_name: django depends_on: - mysql volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.s3 - ./.envs/.local/.mysql ports: - "8000:8000" command: /start restart: unless-stopped platform: linux/x86_64 -
I got this 'TypeError: unsupported operand type(s) for +=: 'CartItems' and 'int' ' error while i am trying to add items to the cart
Views.py: def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create(cart_id=_cart_id(request)) cart.save() try: cart_item = CartItems.objects.get(product=product, cart=cart) cart_item += 1 cart_item.save() except CartItems.DoesNotExist: cart_item = CartItems.objects.create(product=product, quantity=1, cart=cart) cart_item.save() return redirect('cart_app:cart_details') i need cart_item incremented by one when an item is added to the cart -
How do I change the 12 hour format in django?
I have a DateTimeField in my model. When I add this field to admin.py , then the format shows as 4:00 pm , how can this be changed to 16:00? creation_date = models.DateTimeField(auto_now_add=True,) If I do this def time(self): return self.creation_date.timezone().strftime('%Y-%m-%d %H:%M:%S') that time field is not sorted -
what is the proper way to use aggregate in a complicated structured Django models
I have a Django app that represents a football league and should show scores points and other stuff, I need to create a function based on the models in this app to get the sum of goals, points, matches won, and positions in the current season, here are my models : **models.py class TeamName(models.Model): """ Stores Available team name to be picked later by users """ name = models.CharField(max_length=33, verbose_name=_( "Team Name"), help_text=_("Name of the team to be used by players")) logo = models.FileField(upload_to="uploads", verbose_name=_( "Logo Image"), help_text=_("The File that contains the team logo image"), null=True) def image_tag(self): """ This method created a thumbnil of the image to be viewed at the listing of logo objects :model:'teams.models.TeamName' """ return mark_safe(f'<img src="/uploads/{self.logo}" width="100" height="100" />') image_tag.short_description = _("Logo") image_tag.allow_tags = True class Meta: """ Defines the name of the model that will be viewied by users """ verbose_name = _("1. Team Name") def __str__(self) -> str: """ Make sure to view the name as string not the id or pk """ return str(self.name) class TeamStrip(models.Model): """ Stores Available team Strip to be picked later by users """ image = models.FileField(upload_to="uploads/uploads", verbose_name=_( "Team Strips"), help_text=_("A Strip to be used later by users")) … -
No data displayed in template from Django TemplateView
I am new to Djago and am trying to show the detail of an object from a list. Everything works from the code below except for the small matter of the detaill not being displayed. Here is my view `class PieceDetail(TemplateView): template_name = 'cabinets/piece_detail.html' def get_context_data(self, **kwargs): id = kwargs.get('pk') piece = get_object_or_404(Piece, pk=id) pprint(piece.pk) serializer = PieceSerializer(piece) pprint(serializer.data) return {'serializer': serializer, 'cabinets/piece_detail': piece.pk} Here is the urlpath('piece_detail/int:pk/', views.PieceDetail.as_view(), name = 'piece_detail'),` Here is the html {% extends "shared/base.html" %} {% load static %} {% block content %} </br> <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <div class="btn-toolbar mb-2 mb-md-0"> <div class="btn-group me-2"> <a href="/cabinet/piece_list" ><button class="btn btn-primary"> Back </button></a> </div> </div> <br class="modal-body py-0"> <p>{{ serializer.data.id }}</p> <div class="container"> <div class="form-group"> {{ piece.description }} </div> <div class="form-group"> {{ piece.quantity }} </div> </div> </div> <p>The quantity shown is that usually used during construction of components</p> </div> {% endblock %} and here is some pprint output from the terminal on show detail selected 1 {'description': 'door rail', 'quantity': 2} [03/Nov/2023 12:16:05] "GET /cabinet/piece_detail/1/ HTTP/1.1" 200 14603 I have tried various different methods to get the data from the view to the template, but it still seems to go … -
How to implement accurate (hight resolution) zoom on DICOM images?
I use Pydicom and matplotlib to read and display DICOM images in a djANGO PROJECT inspired by Gregorio Flores dicom_django_viewer (thank to him). He use wheelzoom to add zoom fonctionnality but it seems that dicom image loss resolution when zoom is applied. Is there an efficient solutio to implement zoom on DICOM images? -
Infinite redirect loop on login after upgrade from Django 3.2 to 4.2
I've just upgraded from Django 3.2 to 4.2. All my tests now pass and runserver starts without issues. But then I get an infinite redirection loop when I try to display the home page: [03/Nov/2023 10:52:39] "GET /home/ HTTP/1.1" 302 0 [03/Nov/2023 10:52:39] "GET /accounts/login/?next=/home/ HTTP/1.1" 302 0 [03/Nov/2023 10:52:39] "GET /accounts/login/?next=/accounts/login/%3Fnext%3D/home/ HTTP/1.1" 302 0 [03/Nov/2023 10:52:39] "GET /accounts/login/?next=/accounts/login/%3Fnext%3D/accounts/login/%253Fnext%253D/home/ HTTP/1.1" 302 0 [03/Nov/2023 10:52:39] "GET /accounts/login/?next=/accounts/login/%3Fnext%3D/accounts/login/%253Fnext%253D/accounts/login/%25253Fnext%25253D/home/ HTTP/1.1" 302 0 etc. until the browser detects the loop. Can anybody encountered this before tell me what is the change from Django 3.2 to 4.2 which causes this? I don't really know where to start looking. The exact same code base running in a Django 3.2 virtualenv is unbroken. -
DRF - detail not found if annotate a field from a non-existing-relation
I have a model with a nullable relation. class Relation(models.Model): name = CharField(max_length=255) class MyModel(models.Model): name = CharField(max_length=255) relation = ForeignKey(Relation, null=True, on_delete=models.SET_NULL) I pass the name of the relation into my Serializer. class MyModelSerializer(serializers.ModelSerializer): relation_name = serializers.CharField(read_only=true) class Meta: model = MyModel fields = '__all__' I annotate the relation name in the queryset of my viewset. class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all().annotate(relation_name=F('relation__name') serializer_class = MyModelSerializer Now when I try retrieve an instance of MyModel, which has not a relation to Relation, I got the response: { "detail": "Not found." } Otherwise, if the instance has a relation, the response looks like: { "id": 1, "name": "Test MyModel", "relation": 1, "relation_name": "Test Relation" } I've expected, that the response without a relation would look like: { "id": 1, "name": "Test MyModel", "relation": null, "relation_name": null } Does anyone have in the past a problem with annotation of non existing relation and has an idea how to deal with that? Best regards -
ContentNotRenderedError / image field in serializer (DRF)
I have a model for random Products which has an image field and a default image. I want to make it such that the client doesn't have to send an image when creating a new product through the API (using DRF). Below are the model, serializer and view # Model ... total_stock = models.PositiveIntegerField(default=0) product_image = models.ImageField(upload_to='images', blank=True, default='/static/images/default_product.png') # Serializer class ProductSerializer(serializers.ModelSerializer): product_image = serializers.ImageField(max_length=None, allow_empty_file=False) class Meta: model = Product fields = [ 'total_stock', 'product_image'... ] # View class ProductCreate(generics.CreateAPIView): permission_classes = [IsAuthenticated] queryset = Product.objects.all() serializer = ProductSerializer() In order for the view to accept a payload without an image, I have to modify the serializer like this: class ProductSerializer(serializers.ModelSerializer): product_image = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) # added "required=False" But when I do that, I get the error: The response content must be rendered before it can be iterated over. Request Method: GET Request URL: http://127.0.0.1:8000/product/create/ Django Version: 4.0.5 Exception Type: ContentNotRenderedError Exception Value: The response content must be rendered before it can be iterated over. Exception Location: .../lib/python3.10/site-packages/django/template/response.py, line 127, in __iter__ Python Executable: /.../bin/python Python Version: 3.10.4 ... All the other questions I have investigated are with respect to queries but I'm not making a query … -
Nuxt2-Keycloak-Django Rest Framework Authentication
I've integrated keycloak authentication in my nuxt2 application using nuxt-auth, here my auth configration in nuxt.config.js auth: { strategies: { oidc: { scheme: "openIDConnect", clientId: process.env.KEYCLOAK_CLIENT_ID, endpoints: { configuration: `/keycloak/`, }, responseType: "code", grantType: "authorization_code", scope: ["openid", "profile", "email"], codeChallengeMethod: "S256", token: { property: "access_token", type: "Bearer", name: "Authorization", maxAge: 300, }, refreshToken: { property: "refresh_token", maxAge: 60 * 60 * 24 * 30, }, // acrValues: "1", }, }, redirect: { login: "/", logout: "/", home: `/user`, }, }, Now I want to authenticate my django rest framework API with this client keycloak accesstoken I tried django-oauth-toolkit package for keycloak authentication. and configration INSTALLED_APPS = [ ... "oauth2_provider", "rest_framework", ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), } OAUTH2_PROVIDER = { "SCOPES": { "openid": "OpenID Connect", "profile": "User profile information", "email": "User email address", } } while I tried to call my api with the nuxt keycloak access token it returns me 401-Authentication credentials were not provided. Please help me with this scenario or tell me if it possible to authenticate django APIs with nuxt keycloak accesstoken NB: Client used in nuxt and django are different. -
how to customize nested fields serializer through another serializer in drf
File class and Animation are related together And I want to somehow implement the following code serial = AnimationSerializer(instance=Animation.objects.get(id=animationn_id), fields=["duration", "age_rating", {"file": ["name", "description"]}]) or serial = FileSerializer(instance=File.objects.get(id=file_id), fields=["name", "description", {"animations": {"fields": ["duration", "made_by"], "many": True, "read_only": False}}]) actually i don't want write several serializer class. I want to write as little code as possible to achieve this goal. I want to implement the methods of creation and retrieval and update for two models using 2 serializers so that I can use one of the two serializers to create, retrieve, and update instances of that one model. i have two simple model : class File(models.Model): video = 1 PDF = 2 word = 3 all_types = ( (video, "video"), (PDF, "PDF"), (word, "word"), ) type = models.PositiveSmallIntegerField(choices=all_types) name = models.CharField(max_length=30) description = models.CharField(max_length=50) class Animation(models.Model): file = models.ForeignKey("File", on_delete=models.CASCADE, related_name="animations") duration = models made_by = models..CharField(max_length=30) age_rating = models.PositiveSmallIntegerField(validators=[validators.MaxValueValidator(24)]) and i have these serializer class: class DynamicFieldsCategorySerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed … -
Unknown output_field type in Subquery in Django
I have the following models: class Parent1(models.Model): name = models.CharField(max_length=255) class Parent2(models.Model): parent1 = models.ForeignKey(Parent1) label = models.CharField(max_length=255) class Child(models.Model): parent1 = models.ForeignKey(Parent1) parent2_label = models.CharField(max_length=255) # other fields I am trying to execute the below queries: parent1 = Parent1.objects.first() sq = Child.objects.filter(parent1=OuterRef("parent1"), parent2_label=OuterRef("label")) parents_2 = Parent2.objects.filter(parent1=parent1).annotate(children=Subquery(sq)) So basically what I am trying to execute is if Child model had a fk to Parent2 then I would have prefetched the related child instances of the Parent2 instances. Now at present there is no fk relation between Child and Parent2. The relation is based on the label field between those two. fk will be added later but before that for backwards compatibility I have to execute this query. Now when I try to execute this query then I am getting the following error: FieldError: Cannot resolve expression type, unknown output_field I am using Postgresql db. Now what will be the output_field for the above query that I have to pass? -
save() causing the creation of a new record when trying to update an existing record
So I have the following model: class Session(models.Model): sessionid = models.CharField(max_length=10, primary_key=True) forgepass = models.ForeignKey(ForgeProfile, on_delete=models.CASCADE) programid = models.ForeignKey(TrainingProgram, on_delete=models.PROTECT) program_day = models.IntegerField() hours = models.IntegerField() session_date = models.DateField(default=timezone.now()) verified = models.BooleanField(default=False) def save(self, *args, **kwargs): session_count = Session.objects.all().count() self.sessionid = 'S' + self.forgepass.forgepass + id_gen(session_count) super().save(*args, **kwargs) def __str__(self): return '{} - {}'.format(self.sessionid, self.session_date) When updating an existing record on the backend, a new record will be created with a new sessionid and the updated values instead, while keeping the old record. What exactly am I missing here? -
Django: Streams from cameras stop if there are two of them on a page
I made an application that shows the image from the camera after detection and calculation in real time. I show the video on the site. If I show a stream from one camera <img src="{% url 'video_feed' %}" alt="Video Feed 1" width="800" height="600"> it works perfectly. If there are two streams, but from the same camera - ideal. <img src="{% url 'video_feed' %}" alt="Video Feed 1" width="800" height="600"> <img src="{% url 'video_feed' %}" alt="Video Feed 1" width="800" height="600"> If two streams are from different cameras, it freezes almost completely. I open each stream separately - perfect. http://127.0.0.1:8000/video_feed/ http://127.0.0.1:8000/second_video_feed/ What could be the reason? Even tried threading, but to no avail. The final version of views.py I enclose from django.views.decorators import gzip from .object_counter import CountObject_Camera1, VideoCapture_Camera1, CountObject_Camera2, VideoCapture_Camera2 from django.shortcuts import render import cv2 import threading rtsp_url1 = "rtsp:///cam/realmonitor?channel=1&subtype=00&authbasic=[AUTH]" rtsp_url2 = "rtsp:///cam/realmonitor?channel=1&subtype=00&authbasic=[AUTH]" count_object_instance1 = CountObject_Camera1(rtsp_url1) count_object_instance2 = CountObject_Camera2(rtsp_url2) video_capture1 = VideoCapture_Camera1(rtsp_url1) video_capture2 = VideoCapture_Camera1(rtsp_url2) lock1 = threading.Lock() lock2 = threading.Lock() @gzip.gzip_page def video_feed(request): def generate(camera_instance, count_object_instance, lock): while True: with lock: frame = camera_instance.read() annotated_frame = count_object_instance.process_frame(frame) _, buffer = cv2.imencode('.jpg', annotated_frame) frame_bytes = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n') return StreamingHttpResponse(generate(video_capture1, count_object_instance1, lock1), content_type='multipart/x-mixed-replace; boundary=frame') def … -
Drawing price history chart in Django
i am trying to draw a chart with django, the django view will fake some data(price and timestamp) html will draw line chart using chartjs. The console display chart.js:19 Uncaught Error: This method is not implemented: Check that a complete date adapter is provided. even though i follow this chartjs getting start and include <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> i also run npm install moment chartjs-adapter-moment --save-dev and npm install chart.js My views: def price_history(request, product_id): form = ProductNameForm() product = Product.objects.get(pk=product_id) # Create some dummy price history data for testing price_history_data = [] today = datetime.now() for i in range(1, 11): # Generate data for the last 10 days date = today - timedelta(days=i) price = float(product.current_price - (randint(1, 10) * 10)) # Example: Randomly decrease price price_history_data.append({ 'timestamp': date.strftime('%Y-%m-%d'), 'price': price, }) return render(request, 'price_history.html', {'product': product, 'price_history_data': price_history_data, 'form':form}) My template: {% block content %} <div class="container"> <h1>Price History</h1> <!-- Price history chart container --> <!-- Price history chart container --> <canvas id="priceChart" width="400" height="200"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script> <script> // Extract timestamps and prices let timestamps = {{ price_history_data | safe }}; let prices = timestamps.map(entry => entry.price); timestamps = timestamps.map(entry => entry.timestamp); // Get the canvas element … -
I can't log in with a registered user
I can register my users, but I can't log in with these users. After registering the users, they are automatically logged in, so this is the only moment I can access the Profile area. After logging out, I can't log in any user except my superuser. I have try several ways and can't seem to figure it out. here are my files: #models.py from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("O endereço de email é obrigatório") user = self.model( username=username, email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): user = self.create_user( username=username, email=email, password=password, ) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Cadastro(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=75, unique=True) data = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = "username" EMAIL_FIELD = "email" REQUIRED_FIELDS = ["email"] def __str__(self): return self.username #forms.py from django import forms from base.models import Cadastro from django.contrib.auth.forms import AuthenticationForm class CadastroForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Cadastro fields = ("username", "email", "password") class LoginForm(AuthenticationForm): username = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), required=True ) password = forms.CharField( widget=forms.PasswordInput(attrs={"class": … -
How to set refresh token expire of drf social oauth2?
How can we set refresh token expire of drf social oauth2. I try to use this but not work(Work only access token). OAUTH2_PROVIDER = { 'REFRESH_TOKEN_EXPIRE_SECONDS': 1, #set to 1 second for test 'ROTATE_REFRESH_TOKEN': false, } Anyone can help? -
webRTC audio - Don't know how to resume streaming after closing/stoping it
I was trying webRTC for a chatbot with voice prompts. I was successful on incorporating the voice prompts to the chat, but i have a problem. I noticed the mediaRecorder.stop doesn't stop the streaming, so the red circle in the window will not dissapear. I want it to only be streaming when the user is recording the message. What i tried: I searched other solutions and found that this line will successfully end the streaming: stream.getTracks().forEach( track => track.stop() ); The problem is, I don't know how to resume the streaming after that, the record button turns unresponsive. This is my entire code, sorry for not providing a more compact one, i'm not too keen with javascript to leave things behind: let mediaRecorder; let recordedChunks = []; let isRecording = false; // Track the recording state // Function to start recording function startRecording() { if (mediaRecorder && mediaRecorder.state === 'inactive') { mediaRecorder.start(); isRecording = true; } } // Function to stop recording function stopRecording() { if (mediaRecorder && mediaRecorder.state === 'recording') { mediaRecorder.stop(); isRecording = false; } } // Function to initialize the MediaRecorder function initializeMediaRecorder() { if (!mediaRecorder) { // Initialize the MediaRecorder with audio constraints navigator.mediaDevices .getUserMedia({ audio: … -
Getting this error while using Django Tenant with DRF Exception: Can't create tenant outside the public schema. Current schema is ... while using DRF
So I am using django tenant with django rest framework. I have two created apps users and students. For users I was able to setup the model, serializer and viewset and create users using the viewset with no issues. Mirrored most of the logic for creating users in students but been having issues creating a student using the API. Keep getting the error Exception: Can't create tenant outside the public schema. Current schema is concord. I have tried finding a similar issue on stack overflow but not seen anything similar. Would appreciate any help. Find relevant snippets below # MIDDLEWARE # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#middleware MIDDLEWARE = [ "django_tenants.middleware.main.TenantMainMiddleware", "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.BrokenLinkEmailsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] # ------------------------------------------------------------------------------ SHARED_APPS = ( "django_tenants", # mandatory "dew_school_management_system.school", "django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions", "django.contrib.sites", "django.contrib.messages", "django.contrib.staticfiles", # "django.contrib.humanize", # Handy template tags "django.contrib.admin", "django.forms", "django_filters", "dew_school_management_system.users", "crispy_forms", "crispy_bootstrap5", "allauth", "allauth.account", "allauth.socialaccount", "django_celery_beat", "rest_framework", "rest_framework.authtoken", "dj_rest_auth", "corsheaders", "drf_spectacular", ) TENANT_APPS = ( "django.contrib.auth", "django.contrib.sessions", "dew_school_management_system.users", "dew_school_management_system.students", # Your stuff: custom apps go here ) # https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = list(SHARED_APPS) + [ app for app in TENANT_APPS if app not in SHARED_APPS ] # TENANT CONFIGURATION TENANT_MODEL = "school.School" TENANT_DOMAIN_MODEL = "school.SchoolDomain" I … -
AttributeError: 'Response' object has no attribute 'streaming' in packages\django\middleware\common.py
Using requests we are unable to get a 200 success code due to either a bug in the common file or a wrong way of sending the request or receiving the response. Here are the technical details: Calling script import requests try: post_data = {'langs': langs, 'langs_json': []} # filling post_data.. response = requests.post(api_call_url, json=post_data, verify=False) return response except Exception as e: return JsonResponse({}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) Serving script @csrf_exempt def api_end_point(request): try: data = json.loads(request.body.decode('utf-8-sig')) with open(os.path.join(r'assets\i18n', f'fr.json'), 'w', encoding='utf-8-sig') as f: json.dump(data['langs_json'][0], f) with open(os.path.join(r'assets\i18n', f'en.json'), 'w', encoding='utf-8-sig') as f: json.dump(data['langs_json'][1], f) # All works above.. the issue has something to do with the response itself.. response = JsonResponse(dict(status=True), safe=False, status=status.HTTP_200_OK) response.status_code = 200 # trying to solve.. return response except Exception as e: response = JsonResponse(dict(status=False), safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) response.status_code = 500 # trying to solve.. return response Error msg File "C:\Users\***\Desktop\****\*****\*****\venv\lib\site-packages\django\middleware\common.py", line 112, in process_response if not response.streaming and not response.has_header('Content-Length'): AttributeError: 'Response' object has no attribute 'streaming' common.py snippet def process_response(self, request, response): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then … -
Byte range requests in Django REST + nginx (dokku)
In my Django application, I have a Video model with a file FileField that represents a user-uploaded video. I serve these files via a Django REST API view that looks like this: class VideoViewSet(viewsets.ModelViewSet): queryset = Video.objects.all() serializer_class = VideoSerializer def retrieve(self, request, *args, **kwargs): instance = self.get_object() file = instance.file response = FileResponse( file, as_attachment=True, ) response["Content-Disposition"] = 'attachment; filename="video.mp4"' response["Accept-Ranges"] = "bytes" return response the frontend accesses the video like this: <video playsinline controls> <source type="video/webm" :src="videoUrl"/> <p> Videos are unsupported in your browser </p> </video> The application is deployed using dokku, which has gunicorn and nginx sit in front of Django. The problem is: in production, when the video player is opened, I am unable to seek. The video just proceeds from timestamp 00:00 all the way to the end, even if I drag the video timeline thumb to other positions. I learned that has to do with byte range requests, and not supporting them is the cause of not being able to seek while the video is playing. Adding response["Accept-Ranges"] = "bytes" in my viewset makes it work locally, but when I push to production the problem is still there. What can I do to solve … -
'TranslateCategory' object is not iterable in DRF
I use Django Rest Framework and run my code with gunicorn. And i got this error 'TranslateCategory' object is not iterable. Traceback: Request Method: GET Request URL: http://oralbekov.dias19.fvds.ru/api/translate/categories/1/ Django Version: 3.2.16 Python Version: 3.8.10 Installed Applications: ['jazzmin', 'modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'questions.apps.QuestionsConfig', 'calendartodo.apps.CalendartodoConfig', 'rites.apps.RitesConfig', 'map.apps.MapConfig', 'news.apps.NewsConfig', 'translate.apps.TranslateConfig', 'info.apps.InfoConfig', 'reportederrors.apps.ReportederrorsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/var/www/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/var/www/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/var/www/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/var/www/hajjum/translate/views.py", line 30, in categories_id return Response(serializer.data ,status=status.HTTP_200_OK) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 768, in data ret = super().data File "/var/www/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 253, in data self._data = self.to_representation(self.instance) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 686, in to_representation return [ Exception Type: TypeError at /api/translate/categories/1/ Exception Value: 'TranslateCategory' object is not iterable Here …