Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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}) -
best way to read a very big csv file and iterate over all recods
i have a csv file that has 30000 rows and every row has 20000 columns this csv file has 300mb All the lines of this file should be navigated and the information of each line should be stored in the database after a series of calculations My problem at the moment is very slow loading speed to read the csv file i have tried pandas and autopyxl to do this but all of them were too slow -
Slow Performance with Django and Remote PostgreSQL on Docker - Local vs. Production Environment
I'm encountering a significant performance issue with my Django application when using a remotely hosted PostgreSQL database in a production environment. My setup involves a Django application running locally and connecting to a PostgreSQL database hosted on a server. Local Environment: Both Django and PostgreSQL are running locally. Operations, such as importing 1000 rows from an Excel file, are almost instantaneous. Production Environment: Django is running locally, but PostgreSQL is hosted on a server with the following specs: 4 CPUs, 16GB RAM. The same operation takes about 3 minutes. Docker Compose for Production (docker-compose.prod.yml): version: '3.8' services: db: env_file: - .env image: postgis/postgis:16-3.4 command: ["postgres", "-c", "config_file=/etc/postgresql.conf"] volumes: - postgres_data:/var/lib/postgresql/data - ./postgresql.conf:/etc/postgresql.conf - ./pg_hba.conf:/etc/pg_hba.conf environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} restart: unless-stopped networks: - db_network ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"] interval: 10s timeout: 5s retries: 5 # Other services like backup, pgadmin, etc. networks: db_network: driver: bridge volumes: postgres_data: driver: local driver_opts: type: none device: /var/database/postgres_data o: bind Observations: The server doesn't seem to be under heavy load (low CPU and sufficient RAM). Network ping tests to the server show latency varying from 35ms to over 100ms. I'm trying to understand why there's such a … -
Django: Upload Image to database
I am trying to upload an image from input field but when I check from database (using Value in Editor), it shows blank both binary and text. I'm new to uploading image, so I'm not sure what's missing in my code. I added media root on settings.py and urls.py. Here is my code. models.py class ImageUpload(models.Model): idupload = models.AutoField(db_column='idupload', primary_key=True) image = models.ImageField(db_column='image', upload_to="media/", null=True) description = models.CharField(db_column='description', max_length=50, null=True) class Meta: managed = True db_table = 'image_upload' upload.html <form method="post" action="" enctype="multipart/form-data" > {% csrf_token %} <div class="form-group"> <label>Upload File</label> <input class="form-control" name="image" type="file" required> </div> <div class="form-group"> <label>Description</label> <input class="form-control" name="description" required> </div> <button type="submit" name="upload" class="btn btn-gray-800 mt-2 animate-up- </form> views.py def uploadPayment(request): if request.method == 'GET': return render(request, 'upload.html') if request.method == 'POST': image = request.FILES.get('image') description = request.POST.get('description') Image.objects.create(image=image, description=description) return redirect('/images/') I tried above code but I kept on getting nothing. -
django how to prefetch with an Integer?
models class Challenge(models.Model): name = models.CharField(...) version = models.IntegerField(...) class Workout(models.Model): name = models.CharField(...) version = models.IntegerField(...) # this field may not exist # this is a through table class ChallengeWorkoutRelation(models.Model): challenge_id = models.IntegerField() # for some reason, this is IntegerField, not ForeignKey workout_id = models.IntegerField() # for some reason, this is IntegerField, not ForeignKey version = models.IntegerField(default=0) I want to get all workouts belong to one challenge: for relation in ChallengeWorkoutRelation.objects.filter(challenge_id=challenge.pk, version=challenge.version): workout = Workout.objects.get(id=relation.workout_id) # do something with workout... # another version # workout = Workout.objects.get(id=relation.workout_id, version=challenge.version) Can I optimize this code to get more performance? -
Capture Coordinates on PDF in React.js - Similar to DocuSign clone
I'm working on this project which kind of similar to DocuSign. User will upload a pdf and drags and drops textboxes and will save it as templates. I need to store the x and y coordinates along with the label for that textbox. And when the user re-opens the template, he has to see the pdf along with the fields placed on the pre-set coordinates. This info is used in the backend to generate the output pdf using a python script. I'm done with the python script part and planning to use this in django. I don't know how to achieve the coordinates grabbing part. I researched a bit and found a couple of libraries "react-pdf" for pdf viewing and "react-dnd" for drag and drop. Can I achieve the requirement using these two libraries? If you have any other better suggestions, please let me know. Thank you so much in advance.