Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Request Issue With Django On AWS
I have recently been working on developing an application that can answer questions from documents. It has been going well so far, as the project itself works locally, and answers questions with great accuracy. However, when I brought this project over to AWS, it has incredible difficulty answering the questions, always failing with a 504 error. I am receiving the below error from the web.stdout logs, but I am not sure if this is why its failing, or what is going on. https://i.stack.imgur.com/c2zPq.png The project is programmed in python with a Django front end, and Elastic Beanstalk is being used for deployment. The project can be found here: https://github.com/Nessbound/asop_chatbot/tree/stack-overflow I'm not exactly sure where the error is, so I am posting the whole project. Thanks in advance for any help! -
How would I handle another POST request on my site
Hello in my login site I have a form that sends a POST request on submit. this is how I handle the forms POST request in my view def SignUp(request): if request.method == 'POST': stuff goes here else: form = SignUpForm() return render(request, "index.html", {"form": form}) now in my javascript i want to add another POST request that'll check if the current username within a certain is already taken. I made it and sent the POST to my current view where both this POST request will be handled along with the form POST request. what ends up happening is that SignUp() keeps handling both the POST requests. How do I handle two POST requests in one view? Is there a better way to do all of this? (i would preferably want to stay on this url) tried to read about any way to differentiate between POST requests but found nothing. (i started learning django just a few days ago and im completely lost trying to make this work) -
Django / Pytest / Splinter : IntegrityError duplicate key in test only
I know it's a very common problem and I read a lot of similar questions. But I can't find any solution, so, here I am with the 987th question on Stackoverflow about a Django Integrity error. I'm starting a Django project with a Postgres db to learn about the framework. I did the classic Profile creation for users, automated with a post_save signal. Here is the model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.TextField(max_length=280, blank=True) contacts = models.ManyToManyField( "self", symmetrical=True, blank=True ) And this is the signal that goes with it : def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() post_save.connect(create_profile, sender=User, dispatch_uid="profile_creation") The project is just starting, and for now I only create users in the admin view. With the post_save signal, it's supposed to create a Profile with the same form. Here is the admin setup : class ProfileInline(admin.StackedInline): model = Profile class UserAdmin(admin.ModelAdmin): model = User list_display = ["username", "is_superuser"] fields = ["username", "is_superuser"] inlines = [ProfileInline] I'm using pytest and Splinter for my test, and this is the integration test that don't work : @pytest.mark.django_db class TestAdminPage: def test_profile_creation_from_admin(self, browser, admin_user): browser.visit('/admin/login/') username_field = browser.find_by_css('form input[name="username"]') password_field = browser.find_by_css('form input[name="password"]') username_field.fill(admin_user.username) … -
Django: General Questions about API views
I am working on a project and I have a front-end in React which makes some basic CRUD axios calls to the django server. I am trying to figure the best way to administer my django views to receive and process these requests. I understand this very much depends on the how my application needs to function. But at the moment, I am just trying to create simple views (which joins a couple of data models together and returns) This is the approach in action: class Hero(models.Model): character = models.ForeignKey( Card, on_delete=models.CASCADE, related_name="class_id", null=True ) weapon = models.ForeignKey( Card, on_delete=models.CASCADE, related_name="weapon_id", null=True ) player = models.OneToOneField(Player, on_delete=models.PROTECT, null=True) class Game(models.Model): hero1 = models.ForeignKey( Hero, on_delete=models.PROTECT, related_name="hero1_id", null=True ) hero2 = models.ForeignKey( Hero, on_delete=models.PROTECT, related_name="hero2_id", null=True ) hero3 = models.ForeignKey( Hero, on_delete=models.PROTECT, related_name="hero3_id", null=True ) hero4 = models.ForeignKey( Hero, on_delete=models.PROTECT, related_name="hero4_id", null=True ) and then I would write a view as such, class GameHeroView(APIView): serializer_class = HeroSerializer def get(self, request, id=0): game_id = request.query_params.get("id") if game_id is None: game_id = id # Create an empty list for serialized data serialized_data = [] sql = ( " \ SELECT gh.* \ FROM gauntlet_game gg, \ gauntlet_hero gh \ WHERE gg.id = " … -
Django - Update database entry if it exists or insert new entry combining two tables together (models)
I have an app that merges two excel files into one (data from Students and data from their subjects' grades). Therefore, one table for students and one for the grades. Here is what my models.py looks like: models.py class Students(models.Model): study_program = models.CharField(max_length=40, blank=True, null=True) registration_number = models.IntegerField(blank=True, null=True) id_number_1 = models.FloatField(blank=True, null=True) name = models.CharField(max_length=100, null=True) surname = models.CharField(max_length=100) nationality = models.CharField(max_length=10) . . (many more columns here) . def __str__(self): return self.name + ' ' + self.surname class StudentGrades(models.Model): student = models.ForeignKey(Students, default=None, on_delete=models.CASCADE) subject = models.CharField(max_length=40) # Μάθημα (Subject) subject_code = models.CharField(max_length=20, ) # Κωδ. μαθ. (Subject Code) student_class = models.CharField(max_length=40, ) # Τμήμα Τάξης (Class) . . (many more columns here) . def __str__(self): return self.subject + ' ' + self.student.name + ' ' + self.student.surname The primary key that connects these two is the registration number of the student. Each student has a unique registration number. On the views.py I've created two functions that (one for each table) that saves the excel files' content to the database. Here is the views.py: views.py This function saves the students records to the database. If the student's row has a registration number that is a match, it updates … -
Django Rest Framework - How to store a GIF image
I am working on a Django project using Django Rest Framework, and I am facing an issue related to storing and processing GIF images in one of my models. class GiftCardPlan(model.Model): # ... other fields ... image = ProcessedImageField(null=True, blank=True, upload_to=giftcardplan_image_path, processors=[SmartResize(480, 290, upscale=False)], options={'quality': 100}) serializer class GiftCardPlanSerializer(serializers.ModelSerializer): image = Base64ImageField(read_only=True) I want to handle GIF images properly within the GiftCardPlan model. I've tried different approaches, but none seem to work as expected. My current implementation loses GIF animation during processing. -
Getting error "Unknown command: 'load_data'. Did you mean loaddata?" while running "python manage.py load_data"
While running python manage.py load_data I am getting an error Unknown command: 'load_data'. Did you mean loaddata?. Below I have attached the folder structure where load_data.py is present. I also tried running python -m store_monitor.management.commands.load_data but still not working. -
getting Permission denied: '/vol/web/media' when trying to create file in my django application
Here is my dockerfile. FROM python:3.9-alpine3.13 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./electron /electron COPY ./scripts /scripts WORKDIR /electron EXPOSE 8000 RUN apk add --no-cache --virtual .build-deps gcc musl-dev RUN python3.9 -m venv /py && \ /py/bin/pip install --upgrade pip setuptools wheel && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .temp-deps \ build-base postgresql-dev musl-dev linux-headers && \ mkdir -p /vol/web/media && \ <----- The problem is located at this level /py/bin/pip install -r /requirements.txt && \ adduser --disabled-password --no-create-home ozangue && \ chown -R ozangue:ozangue /vol && \ chmod -R 755 /vol && \ chown -R ozangue:ozangue /vol/web/media && \ chmod -R 755 /vol/web/media && \ chmod -R +x /scripts ENV PATH="/scripts:/py/bin:$PATH" USER ozangue CMD ["run.sh"] I cannot save a model containing a file. Because this file must be saved in /vol/web/media The part of the code that poses a problem is as follows (in views.py): file = request.FILES["excel_file"] file_obj = FileModelXSL(file=excel_file) fichier_obj = fichier_obj.save() in settings.py STATIC_URL = '/static/static/' MEDIA_URL = '/static/media/' MEDIA_ROOT = '/vol/web/media' STATICFILES_DIRS = (BASE_DIR / 'static',) STATIC_ROOT = '/vol/web/static' When I build the container, I don't get any errors but I have the impression that /vol/web/media: mkdir … -
AssertionError: PermissionDenied not raised
I'm new to testing in django , i'm trying to test a view that raises PermissonDenied when the test user is not authenticated , this is part of the view code @login_required def files_raw(request): user = request.user # Get the current user # Initialize the base SQL query base_sql_query = "" # Check user conditions if user.is_superuser: # If the user is a superuser, they can access all data, so no need to change the base query. base_sql_query = "SELECT * FROM files" elif user.groups.filter(name='RNA').exists(): # User is in the 'RNA' group, update the base query to include 'RNA'. base_sql_query = "SELECT * FROM files WHERE files.Sample_id LIKE '%RNA'" elif user.groups.filter(name='WGS').exists(): # User is in the 'WGS' group, update the base query to exclude 'RNA'. base_sql_query = " SELECT * FROM files WHERE files.Sample_id NOT LIKE '%RNA'" else: # If none of the conditions are met, raise a PermissionDenied with a custom error message. print("DEBUG: Conditions not met for user:", user) raise PermissionDenied("You are not authorized to access this data") # Execute the raw SQL query with connection.cursor() as cursor: cursor.execute(base_sql_query) # Initialize an empty list to store the results files = [] # Iterate over the cursor to fetch … -
why i can't run my Django project with : python manage.py runserver
I encountered an error: File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'C:\Users\Youssef\Documents\Hello_Django\import_data' However, I do not have a file named "import_data," and I am not using the path 'C:\Users\Youssef\Documents\Hello_Django\import_data.' This is where I had my previous project, which I have since deleted. i tried this : python manage.py runserver i expect the localhost to my web app -
Can Anyone tell if my ERD(Entity Relation Diagram) is correct or not?
I am creating an ERD for my college project. can anyone tell me if my ERD is correct or not. if not then what are my mistakes. I am creating this ERD from django app. I generated the UML diagram with django-extension. But still my teacher says i need to draw the ERD with rectangles identifying the Entities and such. So this is what is created can anyone confirms if it is right or wrong?? -
Django - Created a web app which is linked to my PSQL, but when inserting data to one of my tables gives error for no ID
I have a table where it has only two columns being exercise_id and muscle_id create table if not exists exercise_muscle( exercise_id INT not null, muscle_id INT not null, primary key (exercise_id, muscle_id), foreign key (exercise_id) references exercise(exercise_id), foreign key (muscle_id) references muscle(muscle_id) ); But when I try and insert data into this with the model seen below model for ExerciseMuscle I get this error where it tries to return exercise_muscle.id, which doesn't exist Error picture I have also checked my django dbshell and it looks all fine \d exercise_muscle Table "public.exercise_muscle" Column | Type | Collation | Nullable | Default -------------+---------+-----------+----------+--------- exercise_id | integer | | not null | muscle_id | integer | | not null | Indexes: "exercise_muscle_pkey" PRIMARY KEY, btree (exercise_id, muscle_id) Foreign-key constraints: "exercise_muscle_muscle_id_fkey" FOREIGN KEY (muscle_id) REFERENCES muscle(muscle_id) And checked my psql table and it doesn't have an id column -
django simple jwt login with OTP without password
i have a django-rest app , for auth system i need help . i want to use JWT for auth (simple_jwt) but i was reading the doc , that i have find that i need to send the password and user to get the token to get login . this is a problem because users dont have the password i'm going to use OTP code to login users I have searched the google and looks like i must code a backend i dont want to make it complicated i want as simple as it can be , i searched and i find something like knox too do it can help me out ? -
How to get all pages awaiting moderation in Wagtail
I'm trying to find a way to query all pages that are currently awaiting moderation. I tried PageRevision.objects.filter(submitted_for_moderation=True).values('page_id'), but it seems to return only a few of them, I don't understand why. If i can get all pages in moderation, then i will be able to get what I really want : all pages awaiting moderation for the user currently logged in. Thanks a lot. -
How to create orders and order items in DRF
I want to know, how efficiently i can create order and its order items in DRF using views and serializers. I am sending many=True for POST request to OrderItemSerializer because i will be having a list of order items and want them to validated at once. My questions: How can I pass and update the order field, which was obtained from creating an order, in each OrderItem object . I want these list of order items to be created at once instead of looping over all and doing OrderItems.objects.create(**validated_data) ? views.py class OrderAPIView(generics.GenericAPIView): permission_classes = [IsAuthenticated] serializer_class = OrderSerializer def get_object(self): return self.request.user def get_queryset(self): ... def get(self, request): ... def post(self, request): serializer = self.serializer_class(data = request.data) if serializer.is_valid(): serializer.validated_data['user'] = self.get_object() order = serializer.save() # create order items return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) serializers.py class OrderSerializer(serializers.ModelSerializer): PENDING, CONFIRMED, SHIPPED = "PENDING", "CONFIRMED", "SHIPPED" OUT_FOR_DELIVERY, DELIVERED, CANCELLED = "OUT_FOR_DELIVERY", "DELIVERED", "CANCELLED" ORDER_STATUS_CHOICES = [ (PENDING, "Order Pending"), (CONFIRMED, "Order Confirmed"), (SHIPPED, "Shipped"), (OUT_FOR_DELIVERY, "Out for Delivery"), (DELIVERED, "Delivered"), (CANCELLED, "Cancelled") ] total_price = serializers.DecimalField(max_digits = 7, decimal_places = 2) user = serializers.SlugRelatedField(slug_field = 'email', read_only = True) user_address = UserAddressSerializer() is_paid = serializers.BooleanField(default = … -
How can I use static img file in windows's django
I'm trying to make django webapplication. It worked on linux and wsl.But now I need to make windows native development environment. However when I try to get the static img file I get following errors. django.core.exceptions.SuspiciousFileOperation: The joined path (C:\tcgcreator\img\devirun.png) is located outside of the base path component (C:\Users\jidpn\tcgcreator_eternal_beta\tcgcreator\static) My settings.py is below(something related to static) DEBUG = True STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") urls ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is something I put in the img tag <img class="img_card" src="/static//tcgcreator/img/devirun.png"> My django version is 4.2.3 and python version is 3.11.4 I looked at Django Suspicious Operation and tried the same thing. But it didn't work for me I'm hoping to find answer to this problem -
Button for adding an instance of formset in Django
I want to create a button for dynamically adding and removing an instance of formset from the displayed page. It is my first experience with formset in Django and I do not know any JavaScript, so I would be grateful for any help. So, lines for the formset in my view look like this: strategy_settings = formset_factory(StrategySettings, extra=1) strategy_form = strategy_settings(request.POST) I believe it is a matter of changing the value of an "extra" attribute, but I do not know how to achieve it in JavaScript. here is my template: {% extends "mainapp/base.html" %} {% block content %} <form method="post" id="strategy-form"> {% csrf_token %} {{ simulation_form.as_p }} {% for form in strategy_form %} {{ form.as_p }} {% endfor %} <button type="button">Add Strategy</button> <button type="button">Remove Strategy</button> <button type="submit" name="save">Submit</button> </form> {% endblock %} Thanks to anyone in advance. -
Handling 401 Unauthorized Error on Page Refresh with JWT and React/Django
I'm developing an authentication application using Django for the backend and React for the frontend. I've implemented JWT Tokens for authentication. When I log in, the HttpOnly cookies (access_token and refresh_token) are set correctly. However, I encounter a 401 (Unauthorized) error in the console when I refresh the page. The error occurs during the GET request to http://localhost:8000/api/get-me/. Issue After successfully logging in, if I refresh the page, I get a 401 (Unauthorized) error in the console for the GET request to the /api/get-me/ endpoint. This behavior is unexpected since the user should still be authenticated after the page refresh. Question How can I ensure that the user remains authenticated even after refreshing the page, and avoid the 401 (Unauthorized) error? Is there something missing or incorrect in my configuration of JWT and cookie handling? Relevant Code urls.py path('token/', views.LoginView.as_view(), name='token_obtain_pair'), path('get-me/', views.GetUserDetailView.as_view(), name='get-me'), path('token-validate/', views.TokenValidationView.as_view(), name='token-validate'), views.py from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.permissions import IsAuthenticated class TokenValidationView(APIView): authentication_classes = [JWTAuthentication] def get(self, request): # If the code reaches here, it means the token is valid return Response({"message": "Token is valid"}, status=status.HTTP_200_OK) class GetUserDetailView(APIView): permission_classes = [IsAuthenticated] def get(self, request): serializer = UserDetailSerializer(request.user) print(serializer.data) return Response(serializer.data) class LoginView(APIView): def post(self, … -
Duplicate MongoDB Records Issue with update_one and upsert under High Traffic
I am currently facing a challenging issue in my Django application integrated with MongoDB, particularly when dealing with high traffic and concurrent users. Despite using update_one with upsert, I'm observing instances where double (at times tripple) records are being created intermittently under these conditions. Below is a simplified example of the code snippet I'm using: from pymongo import MongoClient from rest_framework.views import APIView from rest_framework import status from rest_framework.response import Response from django.conf import settings # MongoDB connection setup client = MongoClient(settings.MONGO_CONNECTION_URL) db = client[settings.DATABASE_NAME] collection = db[settings.COLLECTION_NAME] class UserDataView(APIView): def post(self, request) -> Response: try: # Using update_one with upsert to handle user data updates collection.update_one( {'user_id': request.user.pk}, {'$set': {'data': request.data["data"]}}, upsert=True ) # Returning a successful response with a data-related message return Response( {'message': 'User data successfully updated or created'}, status=status.HTTP_200_OK ) except KeyError as e: # Logging and handling potential errors logger.error(e) # Returning a response for a bad request with a data-related message return Response( {'message': 'Bad request. Please provide the required data'}, status=status.HTTP_400_BAD_REQUEST ) Even with the upsert=True option, duplicate records are created sporadically, and this seems to happen during periods of high traffic and concurrent user activity. I've ensured that the user_id is correctly … -
Django not connected to the Apache server
This error came up when I tried to match Django with Apache 2.4. But when I access the server, I get 500 errors I haven't solved this error yet error code [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] mod_wsgi (pid=16020): Failed to exec Python script file 'C:/Apache24/htdocs/django_file/ranking/ranking/wsgi.py'. [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] mod_wsgi (pid=16020): Exception occurred processing WSGI script 'C:/Apache24/htdocs/django_file/ranking/ranking/wsgi.py'. [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] Traceback (most recent call last):\r [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] File "C:/Apache24/htdocs/django_file/ranking/ranking/wsgi.py", line 19, in <module>\r [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] application = get_wsgi_application()\r [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] ^^^^^^^^^^^^^^^^^^^^^^\r [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] File "C:\\Users\\dkdle\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\django\\core\\wsgi.py", line 12, in get_wsgi_application\r [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] django.setup(set_prefix=False)\r [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] File "C:\\Users\\dkdle\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\django\\__init__.py", line 19, in setup\r [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)\r [Mon Nov 13 20:44:10.540478 2023] [wsgi:error] [pid 16020:tid 1112] [client ::1:51548] ^^^^^^^^^^^^^^^^^^^^^^^\r … -
I am getting Templatesyntax error in my Django app
I’m getting templatesyntax error, invalid block on line 66: ‘static’ ; did you forget to register or load this tag. What am I doing wrong? I have tried to delete and create the html file again but same error. It only happens in one of my files, others are working well -
How to show modal from another html after a successful form submission?
Here is the code I'm currently using. I've been trying to figure out how to solve this but I think I can't since it been hours. Any suggestions and answer will be appreciated. urls.py from django.urls import path from .views import pos, save_pos, receipt app_name = 'pos' urlpatterns = [ path('point-of-sale/', pos, name='point-of-sale'), path('save-pos/', save_pos, name='save-pos'), path('receipt/<int:transaction_id>/', receipt, name='receipt-modal'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from shop.models import Items from .models import Transaction, TransactionItems from .forms import TransactionForm from datetime import datetime from django.http import HttpResponse, JsonResponse import json def pos(request): products = Items.objects.filter(is_sold=False) product_json = [{'id':product.pk, 'name':product.name, 'price':float(product.price)} for product in products] context = { 'products' : products, 'product_json' : json.dumps(product_json) } return render(request, 'pos.html', context) def save_pos(request): pref = datetime.now().year + datetime.now().year i = 1 while True: code = '{:0>5}'.format(i) i += int(1) check = Transaction.objects.filter(code = str(pref) + str(code)).all() if len(check) <= 0: break code = str(pref) + str(code) if request.method == 'POST': form = TransactionForm(request.POST) if form.is_valid(): product_ids = form.cleaned_data.get('product_ids', []) product_quantities = form.cleaned_data.get('product_quantities', []) subtotals = [] for product_id, quantity in zip(product_ids, product_quantities): product = Items.objects.get(id=product_id) product_price = product.price subtotal = quantity * product_price subtotals.append(subtotal) transaction = Transaction.objects.create(code=code) transaction.tendered_amount = request.POST.get('tendered_amount', 0) transaction.amount_change … -
Celery concurrency configuration for long tasks
I'm looking for the right configuration of celery to handle long tasks executed in django. These are the keys of the case: the tasks take several minutes to complete, but the processing is done in a remote server the worker procesing is minimal: it calls a remote API, waits for the response and updates a local database based on the response there are several types of tasks, each task type is enqueued to one queue depending on its type, the queues are dinamic, this is they cannot be defined initially the worker can only execute 1 task of each type. I assumed 1 only worker can manage all the tasks as its processing is low. This is the configuration I have so far: - CELERY_CREATE_MISSING_QUEUES = True - CELERYD_CONCURRENCY = 10 - CELERYD_PREFETCH_MULTIPLIER = 1 The worker is started this way, it should handle any queue: celery -A my_project worker --loglevel=info My celery app is defined this way: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') app = Celery('my_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -
Dynamically address lookup in Django template
I have a form on Django template with 2 fields: POSTCODE and HOUSE_NUMBER. I have a address_find() method in the related view. I need the full address to be displayed when the user fills in these 2 fields without submitting the form. ( In other words, when user enters POSTCODE and HOUSE_NUMBER, before submitting I want to check the address with address_find() method and display the full address under the form) Is it possible to do that in Django templates? or do I need to submit the form to do that? Thanks. -
How to split one video stream into several?
I have a code that outputs annotated images in django. Everything works except for one thing: the streams come from different cameras, but they are all displayed in one place. That is, a frame from one camera, then from another, then from a third. Three separate streams are needed for each. I guess I need to do something with it, return StreamingHttpResponse(generate_frames(), content_type='multipart/x-mixed-replace; boundary=frame') but I don't know what exactly. Help me please def video_stream(request): def generate_frames(): for i, result in enumerate(results): image = result.orig_img detection_results = model(image)[0] detections = sv.Detections.from_ultralytics(detection_results) detections = tracker.update_with_detections(detections) annotated_frame = process_frame(image, stream_index=i) # Pass stream_index to process_frame resized_image = cv2.resize(annotated_frame, (1024, 768)) _, frame = cv2.imencode('.jpg', resized_image) frame = frame.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') return StreamingHttpResponse(generate_frames(), content_type='multipart/x-mixed-replace; boundary=frame')