Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cookie on the same domain is set, but not being sent to another subdomain
I have a django server running on api.domain.lt and sveltekit server running on dev.domain.lt. Due to the separate servers I have a endpoint /csrf that forces to set a cookie if there's none for the frontend, so I could perform any kind of POST requests later. As I can see in the response headers the cookie is being set: Set-Cookie csrftoken=d8nimJM2fXtyPdhra2h8oF36o7juCJKz; Domain=.domain.lt; expires=Tue, 28 Jan 2025 17:35:19 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure But when I perform another request to the server the cookie is not being added to the request,for god damn sakes, whyyyyyy? Even if I open the django server in another tab and view the Cookies in the dev tools, there's nothing. CORS_ALLOWED_ORIGINS = [ "https://domain.lt", "https://dev.domain.lt", "https://api.domain.lt", ] CSRF_TRUSTED_ORIGINS = [ "https://domain.lt", "https://dev.domain.lt", "https://api.domain.lt", ] # This allows us to send requests from dev.domain -> api.domain CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True # The cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent under an HTTPS SESSION_COOKIE_SECURE = True # Is this actually doing anything? CSRF_COOKIE_DOMAIN = ".domain.lt" SESSION_COOKIE_DOMAIN = ".domain.lt" This is how I perform a request to the django server: const res = await fetch( "https://api.domain.lt/........", {credentials: … -
Python Django(?) ORM race conditions
The answer to my question may probably be obvious, but I'd like to find out for myself. I love Django ORM and use it in almost all my projects. I'm currently developing a telegram bot using Pyrogram (available in asynchronous mode with async await + asyncio.run), and I want to use Django ORM in it. Let me give a simplified example of my task. There is a button that is bound to an object in the database, each click of which should decrease a field in one object and increase another field in another, conditionally: obj1 = Object1.objects.get(id=X) if obj1.filed1 > 0: obj2 = Object2.objects.get(id=X2) obj1.field1 += N obj2.field2 += N obj1.save() obj2.save() However, I am worried that this may cause a race condition and the result of executing this code with several simultaneous button clicks may differ from what is expected (both in the if condition and when further saving objects). Please tell me what are the best practices for handling such tasks. Is select_for_update method would cover me needs? If Django ORM is not a good solution for this, what ORMs or database libraries should I look at? If Django ORM is suitable, what exactly is the best … -
appication.view is not getting import in django urls using python community edition please help out
i have been making a django project using pycharm community edition i did install application in settings.py it is not getting import in django urls.py from productapp.Views import Home productapp is my app name and this is query ive writen in django.urls file expecting it to get import in my urls file -
Why is my get_token() not the same as my request.META.get("CSRF_COOKIE")?
Does anyone know why I am encountering this issue? I'm starting to test Angular 17 as a FrontEnd with Django as a Backend, and when validating a form, I encounter the issue that when obtaining my token from Django and sending it in the HTTP header, it doesn't match the token expected by Django. I'm not sure if the problem is that the expected token is not updating with get_token() or if get_token() is returning the incorrect token. settings.py: CSRF_TRUSTED_ORIGINS = [ "http://localhost:4200", ] CSRF_COOKIE_NAME = 'XSRF-TOKEN' CSRF_USE_SESSIONS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_DOMAIN = 'localhost' CSRF_COOKIE_PATH = '/' #En esta sección configuro el CORS CORS_ORIGIN_WHITELIST = [ "http://localhost:4200", ] CORS_ALLOWED_ORIGINS = [ "http://localhost:4200", # Angular ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'X-XSRF-TOKEN', 'x-requested-with', 'Content-Type', '_HttpHeaders', ] csrf-service.service.ts export class CsrfService { private csrfToken: string | null = null; constructor(private http: HttpClient) {} //Obtener el token CSRF getCsrfToken(): string | null { return this.csrfToken; } //Cargar el token CSRF desde el servidor loadCsrfToken(): Observable<any> { const csrfUrl = 'http://localhost:8000/obt_csrf_token/'; return this.http.get<any>(csrfUrl); } //Actualizar el token CSRF en el … -
Django - Cannot Display Elements Based On Field Value
I’m currently building a gaming app where a currently logged in user has access to play different games based on their rank in our application. So if a currently logged in user has a rank of let’s say 100 than all the games with a game rank of 100 and below will be displayed. The rest of the games will be locked. I can’t get this currently fully to work with my code. What do I need to change with my code? If I test using When(game_rank__lte=25, then=Value(True)), that seems to work, I can see both locked and unlocked games based on the value of 25 and less. But when I do When(game_rank__lte=user_profile_rank, then=Value(True)), that doesn’t seem to work. All the games are unlocked and none are locked. The rank of each game is the game_rank field in the Game_Info model. The rank of the currently logged in user is the rank field in the User_Info model. Any help is gladly appreciated. Thanks! models.py class Game_Info(models.Model): id = models.IntegerField(primary_key=True, unique=True, blank=True, editable=False) game_title = models.CharField(max_length=100, null=True) game_rank = models.CharField(max_length=1000, null=True, blank=True) game_image = models.ImageField(default='default.png', upload_to='game_covers', null=True, blank=True) locked_game = models.BooleanField(default=0) unlocked_game = models.BooleanField(default=0) class User_Info(models.Model): id = models.IntegerField(primary_key=True, blank=True) image … -
ImportError: attempted relative import beyond top-level package in Django while importing from different django apps
I am trying to import SignUp model from authentication app into views file of another app named core. Why i am getting this error and how can i solve this? core/views.py from django.http import HttpResponse from django.shortcuts import render from mongoengine import DoesNotExist from ..authentication.models import SignUp def home(request): default_content = { 'title': 'Welcome to College Management System', } # Retrieve the user_id and username from cookies user_id = request.COOKIES.get('user_id') username = request.COOKIES.get('username') if user_id: try: user = SignUp.objects.get(username=username) # Your existing code that uses user_id goes here # For example, you can fetch additional user data using user_id # Update default_content or perform other actions based on user information except DoesNotExist: # Handle the case where the user does not exist return HttpResponse("User does not exist") return render(request, 'core/base.html', {'content': default_content, 'username': username}) authentication/models.py import mongoengine from django.contrib.auth.hashers import check_password class SignUp(mongoengine.Document): email = mongoengine.EmailField() username = mongoengine.StringField(max_length=15) password = mongoengine.StringField() first_name = mongoengine.StringField(max_length=20) last_name = mongoengine.StringField(max_length=20) role = mongoengine.StringField(choices=('admin', 'faculty', 'student')) meta = { 'collection': 'Signup', } def check_password(self, raw_password): return check_password(raw_password, self.password) -
An error occurred (403) when calling the HeadObject operation: Forbidden - Why I'm receiving this error when I try to post an item at AWS S3?
I'm working in an e-commerce Django project and I've made the deployment of the project in an EC2 instance, but now that I'm trying to work again at my Django project I'm receiving this error when I try to create a new item ClientError at /items/new/ An error occurred (403) when calling the HeadObject operation: Forbidden Note that I've tried several different types of bucket policies and no one have work Bucket Policy -> { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": [ "arn:aws:s3:::ecommercesimple", "arn:aws:s3:::ecommercesimple/*" ] } ] } settings.py -> # Amazon S3 settings AWS_ACCESS_KEY_ID = 'xxxxx' AWS_SECRET_ACCESS_KEY = 'xxxx' AWS_STORAGE_BUCKET_NAME = 'ecommercesimple' AWS_S3_SIGNATURE_NAME = 's3v4', AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_VERITY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I appreciate any help! -
Can't solve problem "Page not found (404)" in Django
I have this problem and can not fix it. project = test_dummy app = database This is the error message that I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/templates/htmlcode/homeAntragsteller.html Using the URLconf defined in test_dummy.urls, Django tried these URL patterns, in this order: admin/ [name='login'] [name='index_antragsteller'] The current path, templates/htmlcode/homeAntragsteller.html, didn’t match any of these. database/urls.py urlpatterns = [ path('', views.user_login, name='login'), path('', views.index_antragsteller, name='index_antragsteller'), ] test_dummy/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include("database.urls")), ] my views.py for user_data in example_users: User.objects.get_or_create(email=user_data['email'], password=user_data['password'], telefonnummer=user_data['telefonummer'], vorname=user_data['vorname'], ist_bearbeiter=user_data['ist_bearbeiter'], name=user_data['name'], abteilung=user_data['abteilung']) def user_login(request): create_example_users() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['email'] password = form.cleaned_data['passwort'] if User.objects.filter(email=username).exists(): user_eintrag = User.objects.get(email=username) if user_eintrag.password == password: print("Passwort correct") if user_eintrag.ist_bearbeiter: return redirect('../templates/htmlcode/homeBearbeiter.html') else: return redirect('templates/htmlcode/homeAntragsteller.html') else: if user_eintrag.password != password: return redirect('../templates/htmlcode/login.html') else: return redirect('../templates/htmlcode/error.html') else: return render(request, '../templates/htmlcode/login.html') @login_required def index_antragsteller(request): return render(request, '../templates/htmlcode/homeAntragsteller.html') in the view, I also tried to remove ../ from ../templates/htmlcode/homeAntragsteller.html but it doesn't look like it's having any effect. my folder structure . ├───database │ ├───migrations │ ├───views.py │ └───urls.py ├───test_dummy │ ├───static │ │ └───filesCSS │ ├───templates │ │ ├───bilder │ │ ├───htmlcode │ | | └───homeAntragsteller.html │ │ └───scripts … -
How to set next_url in Middleware?
I'm writing a custom piece of Middleware for my Django project that will redirect every page request to an age gate if the user has not yet confirmed they are old enough to enter the page. I want the age gate page to redirect to their originally requested page when they have confirmed the age gate. My middleware right now looks as follows: from django.shortcuts import redirect class AgeGateMiddleware: EXCLUDED_URLS = ['/preview/agegate'] def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.session.get('agegate') and request.path not in self.EXCLUDED_URLS: request.session['next_url'] = request.path return redirect('/preview/agegate') response = self.get_response(request) return response And my age gate view looks like this: def age_gate_view(request): #Load the original page after checking age gate. next_url = request.session['next_url'] #Register users IP for age gate. x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') try: ip =ip except: ip = 'none' form = AgeGateForm({'ip':ip}) #Store age gate response if request.method == 'POST': form = AgeGateForm(request.POST or None, {'ip':ip}) if form.is_valid(): form.save() request.session['agegate'] = 'welcome' return redirect(next_url) context = { 'form':form, } return render(request,'Academy/agegate.html', context) Right now the Middleware works as intended: It redirects to the age gate if this has not yet been confirmed. However: The … -
Django User Is Logged Out outside the home page
I have a django website. Now the problem is, after I sign in as a User or an Agent, the correct links only show up on my home page. Whenever I visit another page, the correct links are gone and are replaced with 'Sign In' and 'Agent Sign In'. Somehow the user is logged out outside of the home page. How can I solve this? Thanks in advance! My models.py: class CustomUser(AbstractUser): email = models.EmailField(unique=True) groups = models.ManyToManyField(Group, related_name='CustomUser_set', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.') user_permissions = models.ManyToManyField(Permission, related_name='customuser_set', blank=True, help_text='Specific permissions for this user.') is_user = True class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) phonenumber = models.IntegerField() def __str__(self): return f'{self.user.username} Profile' class Agent(AbstractUser): username = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=100) agent_email = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=200) image = models.ImageField(upload_to = 'Images/') bio = models.TextField() instagram = models.URLField(max_length=100) twitter = models.URLField(max_length=100) facebook = models.URLField(max_length=100) linkedin = models.URLField(max_length=100) is_featured = models.BooleanField(default = False) last_login = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) slug = AutoSlugField(populate_from='name') is_staff = models.BooleanField(default=False) groups = models.ManyToManyField(Group, related_name='agent_set', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their … -
nginx proxy_pass not passing request to docker app on port 8000
Here is my nginx.conf file: server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/../staticfiles; } location /api/ { include proxy_params; proxy_pass http://127.0.0.1:8000; } } I checked whether my app is running on port 8000 through docker ps command. Here is the log: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f86d5f013c90 lead-hr-api-backend "bash -c ./run.sh" 18 hours ago Up 18 hours 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp lbhr-backend Nginx error logs: sudo tail -F /var/log/nginx/error.log 2024/01/30 11:51:53 [error] 59675#59675: *283 recv() failed (104: Unknown error) while reading response header from upstream, client: 172.69.165.44, server: leadhr.alexpy.com, request: "GET /api/admin/ HTTP/1.1", upstream: "http://127.0.0.1:8000/api/admin/", host: "example.com", referrer: "https://example.com/api/admin/login/?next=/api/admin/" 2024/01/30 11:52:16 [error] 59675#59675: *283 recv() failed (104: Unknown error) while reading response header from upstream, client: 172.69.165.44, server: leadhr.alexpy.com, request: "GET /api/admin/ HTTP/1.1", upstream: "http://127.0.0.1:8000/api/admin/", host: "leadhr.alexpy.com" Later I dug a bit deeper and found the Unknown error was connection reset by peer. I don't remember how I found the error, but it was that. Interestingly, when I run my api server using gunicorn, it works perfectly. -
Adding new data in the database
Validation error for trade - Sheet None: [{'identifier': [ErrorDetail(string='trade with this identifier already exists.', code='unique')]}, I'm trying to save a list of dictionaries in the database, which I will get from a file. The idea is that if a user upload the same file with just some new data, only the new data needs to be saved. from rest_framework import serializers from apps.trades.models import Trade from rest_framework import serializers class TradeSerializer(serializers.ModelSerializer): class Meta: model = Trade fields = ['identifier', 'issue_date', 'maturity_date', 'invested_amount', 'interest_rate'] -
How can i make ManyToMany admin pannel on django?
I made a ManyToManyField in Django, but it dosen't seem like i can edit it in django admin. After reading some documents, I found out that I needed to add some kind of widget, so I added filter_horizontal=('collections',) (which was shown in Django Admin ManyToManyField) but this seems to cause an error. Here are some codes I used. # models.py class Product(models.Model): date_added = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False,null=True, blank=True) image = models.ImageField(null=True, blank=True) description = models.CharField(max_length=1000, null=True, blank=True) description_image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url @property def descriptionImageURL(self): try: url = self.description_image.url except: url = '' return url ... class Collection(models.Model): title = models.CharField(max_length=200, null=False) product = models.ManyToManyField(Product, related_name='collections', blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title # admin.py from django.contrib import admin from .models import * admin.site.register(Customer) admin.site.register(Product) admin.site.register(Order) admin.site.register(OrderItem) admin.site.register(ShippingAddress) admin.site.register(TextBanner) admin.site.register(FocusSection) class CollectionAdmin(admin.ModelAdmin): filter_horizontal = ('collections',) admin.site.register(Collection, CollectionAdmin) which casues error : <class 'store.admin.CollectionAdmin'>: (admin.E019) The value of 'filter_horizontal[0]' refers to 'collections', which is not a field of 'store.Collection'. I would really appreciate your help. -
Dockerizing Django and Nginx - How can I Retrieve the Client IP Instead of the Bridge Network Gateway IP in Django with Docker?
I'm currently facing an issue with my Django application where, despite including the X-Real-IP and X-Forwarded-For headers in the request, I am still retrieving the gateway IP instead of the actual client IP. I have implemented a middleware to print the headers, and the logs consistently show the gateway IP. Here's a snippet of the relevant headers from the middleware logs: DebugHeadersMiddleware ================================== django_app | HTTP_X_REAL_IP : 172.30.0.1 django_app | HTTP_X_FORWARDED_FOR : 172.30.0.1 django_app | HTTP_HOST : localhost django_app | REMOTE_ADDR : 172.30.0.4 =========================================================== expected HTTP_X_REAL_IP or HTTP_X_FORWARDED_FOR to contain the client's IP, but it seems that the gateway IP is being retained. Current Nginx Configuration: upstream app { server web:8000; #container:port or host:port } server { listen 80; location / { proxy_pass http://app; # pass the request to django # allow django to know the client address proxy_set_header X-Real-IP $remote_addr; #* proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; # pass the host name } location /static/ { alias /app/static/; } location /media/ { alias /app/media/; } error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; } my docker-compose : version: '3.9' services: db: # database config ... web: build: ./src volumes: - ./volumes/data/static:/app/static - ./volumes/data/media:/app/media - ./volumes/log/gunicorn/:/log/gunicorn/ env_file: - .env expose: - "8000" depends_on: - … -
Find graphene mutation/query from WSGIRequest it self
I have a middleware class that's before the request reaches the code itself, I want to figure out what mutation/query is begin called here class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): <--- how to figure it out using the WSGI request data = self.doTheMagic(request) if data: request.data = data response = self.get_response(request) return response -
How to reuse method for different classes?
I have a django app and I have two classes in models.py with an image attribute. And I have some functionality for cropping images in the save method. But the functionality is in both save methods almost identical. models.py: This is class: Animal: class Animal(models.Model): images = models.ImageField( upload_to="media/photos/animals", blank=False, null=False, verbose_name="Foto") def save(self, *args, **kwargs): # Opening the uploaded image if not self.images: return im = Image.open(self.images) if im.mode == "JPEG": pass elif im.mode in ["RGBA", "P"]: im = im.convert("RGB") output = BytesIO() original_width, original_height = im.size elif original_height == original_width: desired_width = 200 desired_height = 200 im = im.resize((desired_width, desired_height), Image.LANCZOS) im.save(output, format='JPEG', subsampling=0, quality=95) output.seek(0) self.images = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.images.name.split('.')[ 0], 'image/jpeg', sys.getsizeof(output), None) super(Animal, self).save() And I have a class Category: class Category(models.Model): images = models.ImageField( upload_to="media/photos/categories", blank=True, null=True, verbose_name="Foto") def save( self, force_insert=False, force_update=False, using=None, update_fields=None ): self.slug = slugify(self.name) if not self.images: return im = Image.open(self.images) if im.mode == "JPEG": pass elif im.mode in ["RGBA", "P"]: im = im.convert("RGB") output = BytesIO() original_width, original_height = im.size elif original_height == original_width: desired_width = 200 desired_height = 200 im = im.resize((desired_width, desired_height), Image.LANCZOS) im.save(output, format='JPEG', subsampling=0, quality=95) output.seek(0) self.images = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % … -
Django Allauth Facebook login send me to "login cancelled" page
I am making an app in Django and using the allauth library to enable Facebook login. I set up everything accordingly in my Django project and the FB Developer console (I am pretty sure of this because my Google login works), but when I click on the "Login with Facebook button", a popup window appears with a Facebook page asking me to login, but my app is already in the login cancelled page in the following URL: "https://www.xxxxxxxxxxxxxx.com/accounts/social/login/cancelled/". If I login in the popup window nothing changes in my app and the popup just closes. The weirdest thing is that I am not getting any error or warning logs. This happens both in development and production mode. I read in other posts that adding "ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'" in settings.py can solve the issue, but it did not work for me. Has anyone had a similar problem and know the solution to this? -
Django Rest Framework - Vue js - axios , i cant send session Cookie at DRF api
i try to do a simple session authentication with "django.contrib.auth.urls". While i can login and i recieve a session id and csrf, the first time i login sends at request the cookie when i perform an axios get request, but when i try to login from another account does not send the cookie and i receive error code 401 when i perform a get requst with axios.(I work at development server). I mention also that every time i can do login succesfully and i receive session id and csrftoken but not include them at get request. Here is the settings.py: """ Django settings for inventoryapi project. Generated by 'django-admin startproject' using Django 5.0. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', … -
How to re-implement Django Authentication middleware
Current 'django.contrib.auth.middleware.AuthenticationMiddleware', Is logging in the user and such but using different JWT token from different generated sources (ex apple google github) will not work with this one because it's accepting only and only the one from GRAPHQL_JWT = { "JWT_ALLOW_ANY_CLASSES": [ "graphql_auth.mutations.Register", "graphql_auth.mutations.ObtainJSONWebToken", ], "JWT_VERIFY_EXPIRATION": True, "JWT_LONG_RUNNING_REFRESH_TOKEN": True, "JWT_EXPIRATION_DELTA": timedelta(days=365), "JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=365), } I've already implemented a custom middleware "CustomAuthenticationMiddleware" and It works fine but I need to remove the already existing auth middleware and I get this error django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. -
How to play ffmpeg dash?
I have following code to create chunk of video. permission_classes=[AllowAny] video_serializer = serializers.video_serializer def process_video(self, video_path, video_id): # Set the path where the processed videos will be saved output_dir = os.path.join(settings.MEDIA_ROOT, 'processed_videos') # Create the output directory if it doesn't exist os.makedirs(output_dir, exist_ok=True) # Add your ffmpeg_streaming code here to process the video full_video_path = os.path.join(settings.MEDIA_ROOT, str(video_path)) print(video_path) video = ffmpeg_streaming.input(full_video_path) print(video) # Add your ffmpeg_streaming code here to process the video _144p = Representation(Size(256, 144), Bitrate(95 * 1024, 64 * 1024)) _240p = Representation(Size(426, 240), Bitrate(150 * 1024, 94 * 1024)) _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) dash = video.dash(Formats.h264()) dash.representations(_144p, _240p, _360p, _480p, _720p) dash.output(os.path.join(output_dir, f'dash-stream-{video_id}.mpd')) def post(self,request): try: video_data = self.video_serializer(data=request.data) video_data.is_valid(raise_exception=True) data = video_data.validated_data video_instance = Video.objects.create( id = data.get('id'), saved_location = data.get('video') ) video_instance.save() self.process_video(video_instance.saved_location, video_instance.id) return Response({"success":True}) except Exception as e: return Response({"success":False,"message":str(e)}) This code is working well as it has created different chunk files as well as a .mpd file of a video inside media/processed_video folder. Then I wrote following code to stream that video using that .mpd folder. … -
How to correctly pass merged pdfs as _io.BytesIO object into Django FileResponse()?
I try to merge some pdfs with pypdf and I sadly new Document is an empty page... Any help is apreciated! Thanks in advance! current_time = datetime.now().strftime("%m-%d-%Y_%H.%M") obj_list = request.GET.getlist('PDFobj') qs = CertificatePDF.objects.filter(id__in=obj_list) pdfs = [] for pdf in qs: path = pdf.location.path pdfs.append(PdfReader(path)) merger = PdfMerger() for pdf in pdfs: merger.append(pdf) temp = io.BytesIO() merger.write(temp) merger.close() temp.seek(0) fn = f'DocuName_{str(current_time)}.pdf' return FileResponse(temp, as_attachment=True, filename=fn) I tried with HttpResponse file/attachment also... without any sucess -
I want to add my scrips in views.py Django
I just started working on python using Django! i was referring to some video they showed how display content on browser In Views.py directly using HttpResponse Code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def say_hello(request): return HttpResponse('Hello') Using a custom template (Html) code : from django.shortcuts import render from django.http import HttpResponse # Create your views here. def say_hello(request): return render(request, 'hello.html') But I have my Python script which is myscript.py (root folder) How i can run this script in view.py -
Running Daphne with a Configuration File Similar to Gunicorn in Django - How to Specify Configuration Options
I am working on a Django project and have successfully used Gunicorn with a configuration file (lu_development/gunicorn.conf.py). I am able run my server using this command. gunicorn -c lu_development/gunicorn.conf.py lu_development.wsgi:application Now, I need to switch to Daphne for ASGI support, but I'm unsure about how to specify configuration options for Daphne, similar to what I did with Gunicorn. How can I run Daphne with a configuration file? What is the equivalent Daphne command to gunicorn -c lu_development/gunicorn.conf.py lu_development.wsgi:application? Are there any specific parameters or considerations when using a Daphne configuration file? I would appreciate any guidance or examples on running Daphne with a configuration file, and any insights on differences or similarities between Gunicorn and Daphne configuration setups. Thanks! -
Swagger UI customization in DRF (Django) using drf-spectacular
I am currently trying to document apis of my DRF project. I have read many articles on how to customize swagger api definition . I have found out that i can use extend_schema() and serializers to customize api definitions. But the problem is i have to 100s of APIs in my project. and using extend_schema() i will have to edit 100s of files. Is there a way to define all APIs in a single file ? like for this example : https://editor.swagger.io/ there is a yml file, where we can edit all API definitions. is there something similar that i can do for my DRF project ? -
problem in django login with correct password and phone number
good day. I'm trying to login with phone and password but i can't and I get an error : 'invalid phone number data' and in admin panel password = Invalid password or unknown encryption algorithm what do i do? I also set backend authentication in setting: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'account.authentication.EmailAuthenticationBackend', 'account.authentication.PhoneAuthenticationBackend', ] view: class LoginView(View): def get(self, request):enter code here if request.user.is_authenticated: return redirect('home:home') form = LoginForm() return render(request, 'account/login.html', {'form': form}) def post(self, request): form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['phone'], password=cd['password']) if user is not None: login(request, user) return redirect('home:home') else: form.add_error('phone', 'invalid phone number data') else: form.add_error('phone', 'invalid data')" return render(request, 'account/login.html', {'form': form})