Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: create record from form post in another app
I have 3 apps within a project: registrations Model Registration learners Model:Learner track Model: LearnerTrack When I create a learner object I've a view in learner_track which had been receiving the learner instance and creating relevant tracking records based on the course the learner was registering on. However, when creating a foreign key relationship it stops working and gives an error: Cannot assign "UUID('11456134-fab7-41f7-a7be-6bdaf423d1c6')": "LearnerTrack.learnerId" must be a "Learner" instance. Learner model.py class Learner(models.Model): class Status(models.TextChoices): LIVE = 'Live', 'Live' COMPLETE = 'Complete', 'Complete' DEFERRED = 'Deferred', 'Deferred' WITHDRAWN = 'Withdrawn', 'Withdrawn' status = models.CharField( max_length=25, choices = Status, default = Status.LIVE ) learnerId = models.UUIDField(primary_key=True, default=uuid.uuid4) contractId = models.PositiveIntegerField(default = 1) firstname = models.CharField(max_length=150) middlename = models.CharField(max_length=150, blank=True, null=True) surname = models.CharField(max_length=150) uln = models.ForeignKey(Registration, on_delete=models.CASCADE) postcode = models.CharField(max_length=8) area = models.CharField(max_length=10) created = models.DateTimeField(auto_now_add=True) funding = models.SmallIntegerField() groupId = models.ForeignKey(Group, on_delete=models.PROTECT) courseId = models.ForeignKey(Course, default = 'WMCASec', on_delete=models.CASCADE) postcode_code = models.FloatField(default=1.0) notes = models.TextField(blank = True, null = True) objects = models.Manager() #The default manager live = LiveManager() complete = CompleteManager() deferred = DeferredManager() withdrawn = WithdrawnManager() def clean(self): if self.postcode: self.postcode = self.postcode.replace(" ","").upper() #all postcode data saved in same way def __str__(self): return f"{self.learnerId}" def get_absolute_url(self): … -
"collectstatic" takes too long with Cloudinary, works instantly with local storage
I'm having a serious issue with Django's collectstatic command when using Cloudinary for static file storage. The command takes an unreasonable amount of time to complete, but when I switch to local storage, it runs in under a second. My Setup: Django Version: 5.0.7 Cloudinary Storage Backend: cloudinary_storage.storage.StaticHashedCloudinaryStorage Local Storage: Runs instantly Cloudinary Storage: Takes several minutes (or longer) My settings.py: CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get('CLOUD_NAME'), 'API_KEY': os.environ.get('API_KEY'), 'API_SECRET': os.environ.get('API_SECRET'), } STORAGES = { 'default': { 'BACKEND': 'cloudinary_storage.storage.MediaCloudinaryStorage', }, 'staticfiles': { 'BACKEND': 'cloudinary_storage.storage.StaticHashedCloudinaryStorage', }, } STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" Increasing verbosity: python manage.py collectstatic --noinput --verbosity=3 This shows that the process hangs when checking if files exist on Cloudinary. Using --clear flag: python manage.py collectstatic --noinput --verbosity=3 --clear Didn't help with the speed. Temporarily switching to local storage: This solves the issue, but I need to use Cloudinary in production. Increasing Cloudinary timeout: I added a TIMEOUT value to my Cloudinary configuration, but this also didn't resolve the issue. Using --ignore-existing: Found out that this option doesn't exist in Django. My Cloudinary Status: There was a recent issue with Cloudinary's Aspose Document Conversion Addon, which was marked as resolved. However, the … -
moving python project to another pc without installing packages
I have a project that work with python and some packages and use venv. I compress and transfer it to another pc . the packages are in the site-packages folder .when i write command python manage.py runserver it doesnt work . I try to use python.exe in Scripts folder of my venv but it doesnt work . Also i change path in cfg and activate file but still not working . Do you have oponion or suggestion or another way to do that? Do you have oponion or suggestion or another way to do that? -
django improve performance in dumping data
I have a main model called MainModel and n models ModelA, ModelB ... related with MainModel with a ForeingKey. I want to export n csv each one made from 10k MainModels . This is the code: import csv import io import boto3 from django.core.management.base import BaseCommand from django.conf import settings import datetime import time MODELS = [ 'ModelA', 'ModelB', 'ModelC', 'ModelD', 'ModelE', 'ModelF', 'ModelG', 'ModelH', 'ModelI', 'ModelJ', 'ModelK', 'ModelL', 'ModelM', 'ModelN', 'ModelO', 'ModelP', 'ModelQ', 'ModelR', 'ModelS', 'ModelT', 'ModelU', ] CHUNK_SIZE = 10000 class Command(BaseCommand): help = 'Dump data of all models related to a given club_id into multiple CSV files on S3' def add_arguments(self, parser): parser.add_argument('club_id', type=int, help='The club_id for filtering the data') parser.add_argument('operation_id', type=str, help='The rsync operation ID to structure the folder on S3') parser.add_argument('--output', type=str, default='output.csv', help='Base output file name (default: output.csv)') def handle(self, *args, **kwargs): club_id = kwargs['club_id'] operation_id = kwargs['operation_id'] output_file = kwargs['output'] # Retrieve models using the name in MODELS models = [get_model_from_name(model_name) for model_name in MODELS] s3 = boto3.client('s3') bucket_name = 'your-s3-bucket-name' server = settings.MY_ENVIRONMENT if settings.MY_ENVIRONMENT else "default_env" folder_name = f"{server}-{operation_id}/data" mainmodel = MainModel.objects.filter(club_id=club_id) total_sessions = mainmodel.count() all_fields = sorted(sorted(set(field.name for model in models for field in model._meta.fields)) + ['model']) for start in … -
Django POST not entering data into SQLLiteDB -form not valid
I am trying to get my post data into my SQL database but I just get forms not valid: questions.html (Trimed since the same code is repeated for question2 and question3 replace question1 in code <form action = "" method = "POST"> {% csrf_token %} <div> <p class="t1">Top management demonstrates business continuity leadership and commitment</p> </div> <table class="center"> <thead> <tr> <th>Risk Area</th> <th>Not Sure</th> <th> 1 - Not at All</th> <th> 2 - Somewhat</th> <th>3 - Average</th> <th>4 - Above Average</th> <th>5 - Outstanding</th> </tr> </thead> <tbody> <td colspan="7">{{ topic.0 }}</td> {% for question in questions1 %} <tr> <td class="question">{{question}}</td> {% for n in nchoices %} {% if n == 0 %} <td> <input name= {{question.id}} type="radio" value={{ n }} id="{{name}}" /><lable> Not Sure</lable> </td> {% else %} <td> <input name={{question.id}} type="radio" value={{ n }} id="{{name}}" /><lable> {{n}}</lable> </td> {% endif %} {% endfor %} </tr> {% endfor%} {% endfor%} </table> </table> <h4>Enter any comments about your responses to the questions</h4> <textarea name="{{ textname }}">"Enter Comments Here"</textarea > <input type="submit"> </form> models.py class Answer(models.Model): value = models.IntegerField(null = True) name = models.CharField(max_length=20, null = True) # q_id = models.CharField(max_length=10, default="XX") # USed foreignkey instead question = models.ForeignKey( Question, on_delete=models.CASCADE, null … -
Celery with Redis as Broker Fails with SSL Warnings and Build Fails on DigitalOcean App Platform
I'm deploying a Django app on DigitalOcean's App Platform, using Celery for background tasks with Redis as the broker (Upstash Redis). When I deploy the app on DigitalOcean, I keep getting SSL-related warnings, and eventually, the build fails. Here is the repeated warning that I see in the logs: WARNING/MainProcess: Secure redis scheme specified (rediss) with no ssl options, defaulting to insecure SSL behavior. Setting ssl_cert_reqs=CERT_NONE when connecting to redis means that celery will not validate the identity of the redis broker when connecting. This leaves you vulnerable to man-in-the-middle attacks. When I configure ssl_cert_reqs to CERT_REQUIRED, the warnings still persist, and my deployment fails with the following log (partial): [2024-08-23 20:09:15,471: INFO/MainProcess] Connected to rediss://default:**@refined-cub-54199.upstash.io:6379// [2024-08-23 20:09:15,472: WARNING/MainProcess] Secure redis scheme specified (rediss) with no ssl options, defaulting to insecure SSL behaviour. Here is the relevant part of my settings.py file: CELERY_BROKER_URL = 'rediss://default:<password>@refined-cub-54199.upstash.io:6379' CELERY_RESULT_BACKEND = 'rediss://default:<password>@refined-cub-54199.upstash.io:6379' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kuala_Lumpur' CELERY_REDIS_BACKEND_USE_SSL = { 'ssl_cert_reqs': 'CERT_REQUIRED', 'ssl_ca_certs': BASE_DIR / 'certs/upstash-ca-chain.pem', } CELERY_BROKER_TRANSPORT_OPTIONS = { 'visibility_timeout': 3600, 'ssl': { 'ssl_cert_reqs': 'CERT_REQUIRED', 'ssl_ca_certs': BASE_DIR / 'certs/upstash-ca-chain.pem', } } I have tried the following: Setting ssl_cert_reqs to CERT_NONE, which reduces the warnings but doesn't … -
How to get single nested child object in parent serialized object when models are foreign key related?
I have related models like: class ModelC(models.Model): name = models.CharField() class ModelA(models.Model): state = models.Charfield() modelc = models.ForeingKey(ModelC, through='ModelAModelCRelation') class ModelAModelCRelation(models.Model): modelc = models.ForeignKey(ModelC) modela = models.ForeignKey(ModelA) class ModelAChild(models.Model): parent_model = models.ForeignKey(ModelA) active = models.BooleanField(default=True) type = model.CharField(choices=['a', 'b', 'c', 'd']) updated_at = models.DateTimeField() ModelC is related to ModelA with many to many relation, ModelA is related to ModelC throug ModelAModelCRelation relation, ModelAChild is related to ModelA with ForeignKey, which have many records related with ModelA record And the related serializers are: class ModelCSerializer(serializers.ModelSerializer): modelA_objects = ModelASerializer(many=True, read_only=False) class Meta: model = ModelC fields = StateBaseSerializer.Meta.fields + [ "id", "name", "modelA_objects", ] class ModelASerializer(serializers.ModelSerializer): modelAChild_objects = ModelAChildSerializer(many=True, read_only=True) class Meta: model = ModelA fields = ( 'id', 'state', 'modelAChild_objects', ) class ModelAChildSerializer(serializers.ModelSerializer): class Meta: model = ModelAChild fields = ( 'id', 'active', 'type', ) This approach is returning result like this: [ { 'modelC_obj': { 'id': x, 'name': 'object name', 'modelA_obj': [ { 'id': 1, 'state': 'state name', 'modelAChild_obj': [ { 'id': 1, 'active': true, 'type': 'a' }, { 'id': 2, 'active': false, 'type': 'b' }, { 'id': 3, 'active': true, 'type': 'd' }, ] } ] } } ] But, I need a serialized result like: [ { 'modelC_obj': … -
Troubling while deploying my django app on render with dockerized dataabase
I am having trouble while deploying my Django application on render. I used the render Postgres database which expired and deleted. So, that's why I am trying to use a dockerized database so that it doesn't have any time limit and database accessibility for a lifetime. After containerizing my Django application, it works well on my local machine and I could push it on the docker hub. Whatever, as my application was pre-deployed and configured with the main branch. I am having this error: OperationalError at / could not translate host name "db_social" to address: Name or service not known Request Method: GET Request URL: https://network-project-5q7j.onrender.com/ Django Version: 5.0 Exception Type: OperationalError Exception Value: could not translate host name "db_social" to address: Name or service not known Exception Location: /opt/render/project/src/.venv/lib/python3.11/site-packages/psycopg2/__init__.py, line 122, in connect Raised during: network.views.index Python Executable: /opt/render/project/src/.venv/bin/python3.11 Python Version: 3.11.3 Python Path: ['/opt/render/project/src', '/opt/render/project/src/.venv/bin', '/opt/render/project/python/Python-3.11.3/lib/python311.zip', '/opt/render/project/python/Python-3.11.3/lib/python3.11', '/opt/render/project/python/Python-3.11.3/lib/python3.11/lib-dynload', '/opt/render/project/src/.venv/lib/python3.11/site-packages'] Server time: Fri, 23 Aug 2024 10:12:12 +0000 This is what I got on render. I would like to share my docker-compose.yml version: "3.11" services: db_social: image: postgres volumes: - ./data/db_social:/var/lib/postgresql/data environment: - POSTGRES_DB=social - POSTGRES_USER=postgres - POSTGRES_PASSWORD=qnr63363 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code … -
confusion during make docker serve static files(configuration issue)
My problem was just to configure my wagtail project settings.py to serve static file correctly and i tried search about this topic but docker + wagtail(wagtail into existed django project) not on internet pls help me if you are good at it: Dockerfile: FROM python:3.9-slim-buster LABEL maintainer="londonappdeveloper.com" ENV PYTHONUNBUFFERED=1 # Copy application files COPY ./requirements.txt /requirements.txt COPY . /app # COPY except_nextgen.sql /docker-entrypoint-initdb.d/except_nextgen.sql #added during uwsgi server COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 # Set up virtual environment RUN python -m venv /py && \ /py/bin/pip install --upgrade pip # Install dependencies RUN apt-get update && apt-get install --no-install-recommends -y \ build-essential \ libpq-dev \ gcc \ exiftool \ imagemagick \ libmagickwand-dev \ libmagic1 \ && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies RUN /py/bin/pip install -r /requirements.txt # Set up directories for static and media files RUN adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts # original:ENV PATH="/py/bin:$PATH" updated(uwsgi):ENV PATH="/scripts:/py/bin:$PATH" ENV PATH="/scripts:/py/bin:$PATH" # ENV PATH="/py/bin:$PATH" USER app CMD ["run.sh"] settings.py: import os from django.utils.translation import gettext_lazy … -
How can I safely use multiprocessing in a Django app?
I’ve read the docs suggesting that multiprocessing may cause unintended side effects in Django apps or on Windows, especially those connected to multiple databases. Specifically, I'm using a function, load_to_table, to create multiple CSV files from a DataFrame and then load the data into a PostgreSQL table using multiprocessing. This function is deeply integrated within my Django app and is not a standalone script. I am concerned about potential long-term implications if this code is used in production. Additionally, if __name__ == '__main__': does not seem to work within the deep files/functions of Django. This is because Django's management commands are executed in a different context where __name__ is not set to "__main__", which prevents this block from being executed as expected. Moreover, multiprocessing guidelines recommend using if __name__ == '__main__': to safely initialize multiprocessing tasks, as it ensures that code is not accidentally executed multiple times, especially on platforms like Windows where the module-level code is re-imported in child processes. Here is the code I am using: import os import glob import shutil from multiprocessing import Pool, cpu_count from functools import partial def copy_to_table(connection, file_name: str, table_name: str, columns: list): cursor = connection.cursor() with open(file_name, "r") as f: cursor.copy_from(f, … -
Django Admin Site Not Enforcing Two-Factor Authentication (2FA) with django-otp and django-two-factor-auth
Problem Description: I am trying to enforce two-factor authentication (2FA) for the Django admin site using the django-otp and django-two-factor-auth packages. Despite following the setup steps, the admin login does not require 2FA and allows users to log in with just their username and password. My Setup Django Version: 4.2.11 django-otp Version: 1.5.2 django-two-factor-auth Version: 1.17.0 Python Version: 3.10 What i've done Installed Required Packages: pip install django-otp django-two-factor-auth Updated INSTALLED_APPS in settings.py: INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django_otp', 'django_otp.plugins.otp_email', 'two_factor', 'two_factor.plugins.email', ... ] Configured Middleware in settings.py: MIDDLEWARE = [ 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'two_factor.middleware.threadlocals.ThreadLocals', ... ] Patched the Admin Site in urls.py: from django.contrib import admin from two_factor.admin import AdminSiteOTPRequired admin.site.__class__ = AdminSiteOTPRequired urlpatterns = [ path('admin/', admin.site.urls), path('account/', include(('two_factor.urls', 'two_factor'), namespace='two_factor')), ... ] 2FA Settings in settings.py: TWO_FACTOR_PATCH_ADMIN = True TWO_FACTOR_LOGIN_URL = 'two_factor:login' LOGIN_REDIRECT_URL = '/admin/' LOGIN_URL = 'two_factor:login' Added 2FA Devices: I added an email device using the two_factor_add management command. The issue Even after following these steps, the admin login page does not prompt for 2FA. It allows me to log in directly with just the username and password, bypassing the 2FA requirement entirely. Errors in logs Here are some relevant log entries when … -
I'm having trouble setting cookies with response.set_cookies it return empty dictionary in request.COOKIES in my Django and React.js using axios
I am developing authentication application using django rest framework and React.js with JWT and it works with login and registering user but when I want to access logged in user detail it says un authenticated it can't get Cookie from request.COOKIES.get("jwt") it returns empty dictionary and it also said in frontend Response Headers This Set-Cookie headers didn't specify a "SameSite" attribute and was defaulted to "SameSite = Lax," and was blocked because it came from a cross-site response... Here is the View.py ... class LoginView(APIView): def post(self, request): email = request.data["email"] password = request.data["password"] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed("Incorrect Email!") if not user.check_password(password): raise AuthenticationFailed("Incorrect Password!") payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'jwt': token } return response class UserView(APIView): def get(self, request): token = request.COOKIES.get("jwt") print(request.COOKIES) if not token: raise AuthenticationFailed("UnAuthenticated 1!") try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed("UnAuthenticated 2!") user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) ... Here is settings.py ... ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ ... 'corsheaders', 'rest_framework', ... ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", … -
Dynamic fields in django admin from __init__ form method
I have some models: class Variation(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class VariationOption(models.Model): value = models.CharField(max_length=100) variation = models.ForeignKey(Variation, on_delete=models.CASCADE) def __str__(self): return self.value class BaseProduct(models.Model): name = models.CharField(max_length=100) variations = models.ManyToManyField(Variation, blank=True) class Product(models.Model): base_product = models.ForeignKey(BaseProduct, on_delete=models.CASCADE, null=True, blank=True) variation_options = models.ManyToManyField(VariationOption, null=True, blank=True) an admin form where i dynamically add fields in init method: class ProductAdminInlineForm(forms.ModelForm): class Meta: model = Product exclude = ['variation_options'] def __init__(self, base_product, *args, **kwargs): super(ProductAdminInlineForm, self).__init__(*args, **kwargs) if base_product: self.base_product = base_product variations = self.base_product.variations.all() for variation in variations: field_name = f'variation_{variation.id}' self.fields[field_name] = forms.ModelMultipleChoiceField( queryset=VariationOption.objects.filter(variation=variation), required=True, widget=forms.CheckboxSelectMultiple, label=variation.name ) here is my admin models: class ProductInline(admin.TabularInline): model = Product exclude = ['variation_options'] form = ProductAdminInlineForm class BaseProductAdmin(admin.ModelAdmin): model = BaseProduct list_display = ['__str__'] inlines = [ProductInline] def get_formset_kwargs(self, request, obj, inline, prefix, **kwargs): return { **super().get_formset_kwargs(request, obj, inline, prefix), 'form_kwargs': {"base_product": obj}, } I'm trying to retrieve dynamic fields that i declare in ProductAdminInlineForm init method in the admin page but it look like ProductInline doesn't call init to retrieve form fields. How can i achieve this ? I tried to overrides get_fields and get_fieldset method in ProductInline class: def get_fieldsets(self, request, obj=None): fieldsets = super(ProductInline, self).get_fieldsets(request, obj) if … -
Unable to Upload Files to S3 from Django on Amazon Lightsail, Despite Working Fine Locally with Same Credentials and Policy
I'm running into an issue where I can successfully upload files to my S3 bucket locally, but I encounter problems when trying to upload from my server. Here are the details: Django Settings Settings.py (relevant parts): STATIC_URL = "https://my-cdn.s3.amazonaws.com/static/" STATICFILES_STORAGE = env("STATICFILES_STORAGE") AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME") AWS_S3_REGION_NAME = env("AWS_S3_REGION_NAME") DEFAULT_FILE_STORAGE = env("DEFAULT_FILE_STORAGE") MEDIA_URL = env("MEDIA_URL") S3 Policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-cdn/*" }, { "Sid": "AllowPutObject", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::id:user/my-cdn" }, "Action": "s3:PutObject", "Resource": "arn:aws:s3:::my-cdn/*" } ] } Issue: Local Environment: Uploading files to the S3 bucket works perfectly. Amazon Lightsail Server: Uploads fail (No logs whatsoever), but the credentials and policy are the same. -
Django SocketIO Connection Fails After RDS Restart – How to Handle Database Connectivity Issues?
I'm developing a Django application using SocketIO for real-time communication, and I'm encountering an issue where SocketIO connections fail after an RDS (Relational Database Service) restart, while my Django HTTP APIs continue to work fine. Problem Description My Django application integrates with SocketIO for real-time features. After an RDS instance restart, the HTTP APIs function normally, but SocketIO connections encounter issues and fail to access database models. Specifically, I get errors related to database connectivity when attempting to handle SocketIO connections. Code Snippets Here's how I configure my ASGI application and handle SocketIO connections: ASGI Configuration (asgi.py): import os from django.core.asgi import get_asgi_application import socketio from backend.socketio import socketio_server os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings.dev') django_asgi_app = get_asgi_application() application = socketio.ASGIApp(socketio_server=socketio_server.socketio_server, other_asgi_app=django_asgi_app) SocketIO Connection Handler: async def on_connect(self, sid: str, environ: dict): try: query_string = environ['asgi.scope']['query_string'] token, chat_id = get_token_chat_id_from_query(query_string=query_string) if not token or not chat_id: raise ConnectionRefusedError("Invalid connection parameters.") user = await get_user_from_token(token=token) chat_obj = await get_chat_from_id(chat_id=chat_id, user=user) await update_all_chat_redis(chat_obj=chat_obj) async with self.session(sid=sid, namespace=self.namespace) as session: session['user_id'] = user.id session['chat_id'] = chat_obj.machine_translation_request_id await self.enter_room(sid=sid, room=chat_id) except ConnectionRefusedError as e: logger.error(f"Connection refused: {e}") raise except UserErrors as exc: logger.error(f"User error: {exc.message}") raise ConnectionRefusedError(exc.message) except Exception as e: logger.error(f"Unexpected error: {e}") raise ConnectionRefusedError("An unexpected error … -
return render(request,"includes/properties.html",{'property':property,'image':image}) NameError: name 'image' is not defined
images = request.FILES.getlist('images') global image for image in images: image = PropertyImage.objects.create(image = image,property = property) return render(request,"includes/properties.html",{'property':property,'image':image}) -
DRF Response field shows List of String with backslashes
I'm creating Polls feature using DRF where users can create a poll. The Response object in postman for the 'options' field shows the List of strings with backslashes. Here is the Postman response : { "id": 17, "question": "Who will win the Fifa World Cup 2026 in USA ?", "options": "[\"Germany\",\"Argentina\",\"France\",\"Italy\",\"Brazil\",\"None of the above\"]", } My code which gives the above result : //views.py// class Polls(APIView): permission_classes = (IsAuthenticated,) def put(self, request): request_data = request.data.dict() serializer = PollPostRequestSerializer(data=request_data, context={"request": request}) serializer.is_valid(raise_exception=True) data = serializer.validated_data question = data.get('question') options = data.get('options') Poll = get_poll_model() poll = Poll.create_poll(question=question, options=options) poll_serialized = PollPostResponseSerializer(poll, many=False, context={"request": request}).data return Response(poll_serialized, status=status.HTTP_200_OK) //Request serializer// class PollPostRequestSerializer(serializers.Serializer): question = serializers.CharField(max_length=1000, required=True, allow_blank=True, allow_null=False) options = serializers.CharField(max_length=1000, required=True, allow_blank=True, allow_null=False) //Response serializer// class PollPostResponseSerializer(serializers.ModelSerializer): class Meta: model = PollPost fields = ( 'id', 'question', 'options', ) //models.py// class PollPost(models.Model): question = models.TextField(blank=False, null=False) options = models.TextField(blank=False, null=False) @classmethod def create_poll(cls, question, options): return cls.objects.create(question=question,options=options) My purpose is to get the Response object without the backslashes. Help appreciated. -
Django Grappelli Custom Dashboard not showing App Models
Django 5.0.1 & Grappelli v4.01 Have site running on local runserver host and the custom dashboard works as expected. Site has been pushed to Azure as an App Service. The custom dashboard only shows the Groups, Sites and Users Models from auth. I am logging in as a superuser in both cases and both the local runserver and app service instances are pointed to the same backend database on Azure. I suspect permissions but not sure why the core models appear but the app based ones don't on the App Service. What am I missing? thanks in advance. -
Youtube transcript API not working on server
I have a Django web app. This code works perfectly fine on localhost but stops working when I run it on cloud (DigitalOcean) App Platform. from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound, VideoUnavailable def transcribe(video_url): video_id = video_url.split("v=")[-1] logger.debug("Extracted video ID: %s", video_id) try: transcript_list = YouTubeTranscriptApi.list_transcripts(video_id) transcript = None for transcript_info in transcript_list: try: transcript = transcript_info.fetch() break except Exception as e: logger.warning("Error fetching transcript: %s", e, exc_info=True) continue if transcript is None: logger.error("No transcripts available for this video.") return "No transcripts available for this video." except TranscriptsDisabled as e: logger.error("Transcripts are disabled for this video. %s", e, exc_info=True) return "Transcripts are disabled for this video." except NoTranscriptFound: logger.error("No transcript found for this video.") return "No transcript found for this video." except VideoUnavailable: logger.error("Video is unavailable.") return "Video is unavailable." except Exception as e: logger.error("Error in fetching transcript: %s", e, exc_info=True) return "Error in fetching transcript." # Concatenate all text from the transcript into a single string transcription_text = ' '.join([item['text'] for item in transcript]) logger.debug("Transcription text (first 50 characters): %s", transcription_text[:50]) return transcription_text The part that throws an exception is the line transcript_list = YouTubeTranscriptApi.list_transcripts(video_id). And it throws a TranscriptsDisabled exception, saying that Transcripts are disabled for this video. … -
How should I learn Django? [closed]
I have tried learning Django in the way I was learning Flask. Looking into documentation and googling phrases like 'Django user', but I find it a lot harder to get what I want. Google shows me links to documentation where there is some info about the topic and a lot of information about anything related. For example when I tried looking for how to implement User model to project I found django.contrib.auth.models - User and links to authentication, but a bit later looking for some examples I found AbstractUser, which I didn't see on the page of documentation I were on... so my question is how should I learn Django? Should I follow some tutorials instead of what I am doing now (trying to make a webpage along learning from documentation)? What is the best way to learn Django? -
Django/NGINX - CSRF verification failed in production on a 3g-enabled device
My django app works perfectly fine on other devices with 4G connectivity. Trying to sign up or login on a device with only 3G capability throws the CSRF verification failed error. Any idea why that is? I'm also using Cloudflare to configure/manage the domain name server. Thanks. I already looked through the settings file (mostly following the docs) but don't wanna to break anything that's already working. Here's my NGINX config: upstream app_server { server unix:/tmp/gunicorn.sock fail_timeout=0; } server { listen 80; client_max_body_size 4G; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name jovimifah.com www.jovimifah.com; keepalive_timeout 5; access_log /home/vickerdent/logs/nginx-access.log; error_log /home/vickerdent/logs/nginx-error.log; location /static/ { root /home/vickerdent/shop-central; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } Also, CSRF_COOKIE_SECURE and SESSION_COOKIE_SECURE are True. -
how to write swagger base on serializer class in django to if we change fields, no need to edit swagger manually
I have end point in Django and I use DRF. I want to swagger generate document base on serializer class but I dont know how to do that. I prompt with chat gpt but there is no solution that i can find and every time generate swagger code with OpenAPI with manual parameters. I give you guys some example of my codes and appreciate to help me. before this view, if I dont have serializer, I write manually with @swagger_auto_schema and give parameters and reponses code manual. please note that I'm new in web development. thanks. class MemberListView(CustomPagedListView, ListAPIView): """ Provides the Organization Member list """ permission_classes = [UserIsOrganizationAdmin] serializer_class = OrganizationMemberRawSerializer page_size = 10 def get_queryset(self): try: query, include_contracts = self.create_query(self.request.GET) sort_by = self.request.GET.get("sort", "name") if include_contracts: organization_members = ( OrganizationMember.existing_objects.prefetch_related( "contracts" ).filter(query) ).distinct() else: organization_members = OrganizationMember.existing_objects.filter( query ).distinct() str_field = self.request.GET.get("query", "").lower() rate = self.request.GET.get("rate", "").strip() if str_field + rate == "": return self.sort_data(organization_members, sort_by) selected_organization_member_ids = [] for item in organization_members: if ( str_field != "" and rate != "" and self.check_str_field_found(item, str_field) and self.check_rate_filter(item, rate) ): selected_organization_member_ids.append(item.id) if ( str_field != "" and rate == "" and self.check_str_field_found(item, str_field) ): selected_organization_member_ids.append(item.id) if ( str_field == … -
django.urls.exceptions.NoReverseMatch error while trying to use reverse
I have a problem with reverse function in Django. In my project I have an app called posts and I am trying to test it. class PostListViewTest(TestCase): def test_future_post_list(self): post = create_post('Future', 2) response = self.client.get(reverse('posts:all')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No posts available") self.assertQuerySetEqual(response.context['posts_list'], []) In main urls.py I have from django.conf import settings from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('posts/', include("posts.urls")), path('aboutme/', include("aboutme.urls")) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in posts/urls.py I have # urls.py from django.urls import path from . import views # Ensure this import is correct urlpatterns = [ path("allposts/", views.AllPostsView.as_view(), name="all"), path("<int:pk>/", views.PostDetailView.as_view(), name="detail") ] but when I am trying to run tests I get django.urls.exceptions.NoReverseMatch: 'posts' is not a registered namespace when I use reverse('all') instead of reverse('posts:all') everything works perfectly Tried to catch typos but didn't fount them -
Django Rest Framework Serializer Not Applying Model Field Defaults
I'm working on a simple Django project from drf documentation where I have a Snippet model that uses the pygments library to provide language and style options for code snippets. I've set default values for the language and style fields in my model, but when I try to serialize this model using Django Rest Framework (DRF), the default values don't seem to be applied while running server. # models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLES = sorted([(style, style) for style in get_all_styles()]) class Snippet(models.Model): title = models.CharField(max_length=50, blank=True, default="") linenos = models.BooleanField(default=False) code = models.TextField() language = models.CharField(choices=LANGUAGES, default="python", max_length=50) style = models.CharField(choices=STYLES, default="monokai", max_length=50) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ["updated_at"] #serializers.py from rest_framework import serializers from .models import Snippet class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = "__all__" def get_initial(self): initial = super().get_initial() or {} initial["language"] = Snippet._meta.get_field("language").get_default() initial["style"] = Snippet._meta.get_field("style").get_default() print(initial) return initial {'title': '', 'linenos': False, 'code': '', 'language': 'python', 'style': 'monokai'} {'title': '', 'linenos': False, 'code': '', 'language': 'python', 'style': 'monokai'} but when I run server … -
Join tables and retrieve columns in Django
I have two tables (with corresponding models): Mapping id parent_id child_id child_qty 1 1 1 5 2 1 2 3 3 1 4 4 4 2 1 3 5 2 3 2 Child id name property 1 name1 prop1 2 name2 prop2 3 name3 prop3 4 name4 prop4 Note: in Mapping model, 'child' is defined as a ForeignKey on Child model, that automatically creates 'child_id' in Mapping table. I want to write a join: SELECT mt.child_id, mt.child_qty, ct.name, ct.property FROM mapping mt, child ct WHERE mt.parent_id = 1; that gives result: child_id child_qty name property 1 5 name1 prop1 2 3 name2 prop2 4 4 name4 prop4 I wrote this: my_qs = Mapping.objects.select_related('child').filter(parent_id=1).values() print(my_qs) # [{'id':1, 'parent_id': 1, 'child_id': 1, 'child_qty': 5}, # {'id':2, 'parent_id': 1, 'child_id': 2, 'child_qty': 3}, # {'id':3, 'parent_id': 1, 'child_id': 4, 'child_qty': 4}] What do I modify in my ORM query so that: I don't see 'id' and 'parent_id' in the output I see 'ct.name and ct.property' in the output (with our without 'ct.' prefix)