Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In my browser console window.crossOriginIsolated is false despite of adding all proper COOP COEP CORP headers in my React Js and Django app
when i access cmd to express-> node server.js with coop and coep and corp headers and access directly the locahost:8080/ everything is working fine and even window.crossOriginIsolated is true. but when i integrate it to my existing react js and django and i add custom middleware.py for coop and coep. but still no use... even the pages of any of my reactjs and django itself is not showing window.crossOriginIsolated true despite of adding all required headers. kindly help me. i dont have any cors error at all my app works fine with api's transaction between react js and django working fine. this is custom middleware for cors `from django.http import HttpResponse class CrossOriginIsolationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Handle OPTIONS preflight request (for CORS) if request.method == 'OPTIONS': response = HttpResponse() response['Access-Control-Allow-Origin'] = 'http://localhost:3000' # Specify the frontend origin response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE' return response response = self.get_response(request) response['Access-Control-Allow-Origin'] = 'http://localhost:3000' response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE' if request.path.startswith('/dicomweb/'): response['Cross-Origin-Opener-Policy'] = 'same-origin' response['Cross-Origin-Embedder-Policy'] = 'require-corp' response['Cross-Origin-Resource-Policy'] = 'cross-origin' # Changed to … -
Django forms.py and Join.html not rendering form errors
I have seen many tutorials on this, (I am new to Django) and the only issue I could find was raise form.Validation("...") was not rendering on my HTML template and did not stop the form from submitting. I tried many options including AI yet I was still running into the same problems. If I have made a silly mistake please point it out so I know for next time, this code is just a project of mine so I can learn how to code Django. HTML: <form id="form" action="" method="post" name="form"> {% csrf_token %} <div class="input-control"> {% if form.non_field_errors %} <div class="error">{{ form.non_field_errors }}</div> {% endif %} {% if form.errors %} <div class="error">{{ form.errors }}</div> {% endif %} <div class="username"> <label for="{{ form.username.id_for_label }}" class="label">{{ form.username.label }}</label> {{ form.username }} <!-- Render the input field --> {% for error in form.username.errors %} <div class="error">{{ error }}</div> {% endfor %} </div> <div class="email"> <label for="{{ form.email.id_for_label }}" class="lemail">{{ form.email.label }}</label> {{ form.email }} {% for error in form.email.errors %} <div class="error">{{ error }}</div> {% endfor %} </div> <div class="password"> <label for="{{ form.password.id_for_label }}" class="label">{{ form.password.label }}</label> {{ form.password }} {% for error in form.password.errors %} <div class="error">{{ error }}</div> {% endfor … -
How Can I Setup Celery in my Flask Project (Beginner)
So I've been working on a project for a couple months now and I've been trying to implement Celery into my flask project and it has not gone well. I thought maybe it's my computer or windows or something like, and all the responses I've seen are from a couple years ago and I don't think that they would still work because those were the ones I tried using. So thank you for any responses in advance. I tried using the celery config from the documentation and some chat gpt tutorials but they haven't been of help. And I'm running redis as the broker and result backend on the localhost -
UnicodeDecodeError: 'UTF-8' codec can't decode byte 0xff in position 0: invalid start byte. DRF
There is a backend on django and a postgres DB that stores data about the item, including pictures. And there is a problem with getting a picture from the database, i've looked at enough solutions, but none of them work. serializers.py import base64 import uuid import imghdr class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): if isinstance(data, str) and 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except (TypeError, ValueError): self.fail('invalid_image') file_name = str(uuid.uuid4())[:12] file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = f"{file_name}.{file_extension}" data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): extension = imghdr.what(file_name, decoded_file) return extension or 'jpg' class CreateItemSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') photo = Base64ImageField(required=True) class Meta: model = CreateItem fields = '__all__' def create(self, validated_data): items = CreateItem.object.create_item( name = validated_data.get('name'), price = validated_data.get('price'), description = validated_data.get('description'), type_item = validated_data.get('type_item'), photo=validated_data.get('photo') ) return items views.py class GetItemView(APIView): serializer_class = CreateItemSerializer def get(self, request): items = CreateItem.object.all() response_data = { 'items': [ { 'photo': item.photo, 'name': item.name, 'description': item.description, 'type_item': item.type_item, 'price': item.price, } for item in items ] } return Response(response_data, status=status.HTTP_200_OK) full error traceback Internal Server Error: /api/v1/item/items-get/ Traceback (most recent call last): File "/home/anton/Documents/e-m/e-market/backend/my_backend/venv_em/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = … -
Using React in existing Django Project
I have an existing Django project. Its a website that displays a map with leaflet. Markers and everything is loaded dynamically from django. Now I want to enhance that with React. In a sense that when you click a marker on the map, react will render based on marker_id the specific marker-details in a sidebar or something. I am not sure how to do that. In the django template I have a onclick event to get the marker-details: marker.uri = `/map/api/marker_details/?marker_id=${marker.marker_id}&marker_type=${marker.marker_type}` marker.on('click', function (e) { jQuery.get(this.uri); }); Since this is all in django template and not in React, the result is probably not accessible via react to render the details. Do I have to implement the map with the marker and everything in React to then be able to render the details via API? What am I missing? -
Graphql Apollo client
I want to send some data to my graphql python django that stores the data to mysql database. The data are week of planting, the block planted and images,videos. Using react as fronted, I have used dropzone in my react. But it just sending empty objects for image and video fields Sending and storing images to mysql db⁷ -
Iframe of the main page without authorization for an authorized user
Django. There was a problem while creating the website page. A user who is registered and authorized on the site should see the main page in an iframe, but as an unregistered user. Is this possible? -
Django /media/ files not served in production on hosting
I really feel like i am stuck, and hosting support doesn't include configuration help so maybe someone here would know i have django server with model: class Video(models.Model): thumbnail = models.ImageField(upload_to='thumbnails/', blank=True, null=True) saved here in folder thumbnails: MEDIA_URL = '/media/' MEDIA_ROOT = '/home/username/domains/domain.com/djangoapp/media' when i later want to use uploaded image in html: <img src="{{ video.thumbnail.url }}" alt="{{ video.title }}" class="video-thumbnail"> it it not served in production (works on debug=True), file not found 404 File is correctly uploaded, but not served I did python3 manage.py collectstatic enter image description here with no result Here's .htaccess file in the domain folder: enter image description here # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/username/domains/domain.com/djangoapp" PassengerBaseURI "/" PassengerPython "/home/username/virtualenv/domains/domain.com/djangoapp/3.7/bin/python" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_URI} ^/media/ RewriteRule ^media/(.*)$ /home/username/domains/domain.com/djangoapp/media/$1 [L] </IfModule> that i tried adding this rule to, with no result. Any ideas on what could i try? Or anybody who had simillar problem? I tried to clear database and migrate it from zero. Tried collecting static. I tried changing rule in .htaccess. I tried running in debug and it worked. -
Mixing gzip & brotli in Django
I have django-brotli installed and use it's middleware. I would like Django to also serve gzipped content in case the client doesn't support brotli. Is it as easy as just adding GZipMiddleware to the middlewares list? I don't want them to potentially mix with eachother. -
We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later [closed]
J'ai un problème actuellement sur mon application. Je l'ai héberger sur LWS et j'ai fait toutes les configuration possible mais j'ai toujours un problème voici se qui est écrit: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later. Technical details for the administrator of this website Error ID: 04580f7c Details: Web application could not be started by the Phusion Passenger(R) application server. Please read the Passenger log file (search for the Error ID) to find the details of the error. You can also get a detailed report to appear directly on this page, but for security reasons it is only provided if Phusion Passenger(R) is run with environment set to development and/or with the friendly error pages option set to on. For more information about configuring environment and friendly error pages, see: Nginx integration mode Apache integration mode Standalone mode This website is powered by Phusion Passenger(R)®, the smart application server built by Phusion®. I have a problem currently on my application. I hosted it on LWS and I did all the possible configuration but I still have a problem here is what is written: We're sorry, but something went wrong. The … -
TypeError at / cannot unpack non-iterable NoneType object (Django)
I'm trying to set up a system on my Django project where users can comment on individual posts on the main (index) page. However, I'm having an issue when it comes to trying to make it so the comment is automatically connected to the post. This is the code I tried in views.py: from django.core import paginator from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from .models import * from django.views.generic import ListView, CreateView, UpdateView from django.views.generic.detail import DetailView from .forms import * from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login from django.core.paginator import Paginator from django.views import View import random def index(request, pk=None, *args, **kwargs): postdata = Post_Data.objects.all() profiledata = ProfileData.objects.all() likedata = Like.objects.all() dislikedata = Dislike.objects.all() comment = PostComment.objects.all() postid = Post_Data.objects.get(pk) # Initialize the comment form if request.method == 'POST': comment_form = PostCommentForm(request.POST) if comment_form.is_valid(): post = comment_form.save(commit=False) post.user = request.user post.save() return redirect('/') else: comment_form = PostCommentForm() # Create an empty form # Pass the comment form to the template context return render(request, 'index.html', { 'title': 'RoamTrip', 'postdata': postdata, 'profiledata': profiledata, 'likedata': likedata, 'dislikedata': dislikedata, 'comment': comment, 'comment_form': comment_form # Make sure this is included }) models.py: from django.contrib import admin from django.db import … -
Django serializer to convert list of dictionary keys to model fields
I am using pandas openpyxl to read excel file in my project. After reading the excel file I end up with list of dictionaries. These dictionaries have keys such as "Year 2024", "Range", "Main Point", and etc. I have a field in my Django app that has these fields such as "year", "range", "main_point". My question is how can I write a serializer to convert dictionary keys to fields in my model? I want to do this in serializer because I also want to validate dictionary data. So I have this list: my_data = [ {"Year 2024": "5", "Range":"2", "Main Point": "OK"}, {"Year 2024": "6", "Range":"3", "Main Point": "OK"}, {"Year 2024": "7", "Range":"4", "Main Point": "OK"}, ... ] and my model class MyModel(models.Model): year = models.IntegerField(...) range = models.IntegerField(...) main_pont = models.CharField(...) Thanks -
How to load chat messages in batches in Django using StreamingHttpResponse?
I'm working on a Django project that streams chat messages between two users using StreamingHttpResponse and async functions. I want to load messages in batches (e.g 20 at a time) instead of loading all the messages at once to optimize performance and reduce initial load time. Here’s my current view code: async def stream_chat_messages(request, recipient_id: int) -> StreamingHttpResponse: """View used to stream chat messages between the authenticated user and a specified recipient.""" recipient = await sync_to_async(get_object_or_404)(User, id=recipient_id) async def event_stream(): async for message in get_existing_messages(request.user, recipient): yield message last_id = await get_last_message_id(request.user, recipient) while True: new_messages = ( ChatMessage.objects.filter( Q(sender=request.user, recipient=recipient) | Q(sender=recipient, recipient=request.user), id__gt=last_id, ) .annotate( profile_picture_url=Concat( Value(settings.MEDIA_URL), F("sender__userprofile__profile_picture"), output_field=CharField(), ), is_pinned=Q(pinned_by__in=[request.user]), ) .order_by("created_at") .values( "id", "created_at", "content", "profile_picture_url", "sender__id", "edited", "file", "file_size", "is_pinned", ) ) async for message in new_messages: message["created_at"] = message["created_at"].isoformat() message["content"] = escape(message["content"]) json_message = json.dumps(message, cls=DjangoJSONEncoder) yield f"data: {json_message}\n\n" last_id = message["id"] await asyncio.sleep(0.1) async def get_existing_messages(user, recipient) -> AsyncGenerator: messages = ( ChatMessage.objects.filter( Q(sender=user, recipient=recipient) | Q(sender=recipient, recipient=user) ) .filter( (Q(sender=user) & Q(sender_hidden=False)) | (Q(recipient=user) & Q(recipient_hidden=False)) ) .annotate( profile_picture_url=Concat( Value(settings.MEDIA_URL), F("sender__userprofile__profile_picture"), output_field=CharField(), ), is_pinned=Q(pinned_by__in=[user]), ) .order_by("created_at") .values( "id", "created_at", "content", "profile_picture_url", "sender__id", "edited", "file", "file_size", "is_pinned", ) ) async for message in … -
__str__ returned non-string (type NoneType). In template /app/test/templates/test/init.html, error at line 0
Получаю следующую ошибку: str returned non-string (type NoneType) In template /app/test/templates/test/init.html, error at line 0 str returned non-string (type NoneType) Шаблон init.html - это базовый шаблон Ошибка происходит на уровне рендеринга шаблона. Из-за чего это может быть? Пробовал отладить, комментировал все места в шаблоне, где могли быть объекты None. Например для: book.author.name проверял, есть ли book.author и т.д. Но это не помогло. Я в django новичок, возможно нужно больше информации? -
Custom permissions in rests framework
I need permissions for my app in DRF. Input: noauthenticated users can only read publication and images authenticated users can create publications and add images authorized users can edit and delete publications and images for which they are authors admin user can do all actions but DELETE content Models: class Publication(models.Model): pub_text = models.TextField(null=True, blank=True) pub_date = models.DateTimeField(auto_now_add=True) pub_author = models.ForeignKey(User, on_delete=models.CASCADE) class Image(models.Model): image = models.ImageField(upload_to='images', null=True) image_to_pub = models.ForeignKey(Publication, on_delete=models.CASCADE, null=True, related_name='images') Views: class PublicationViewSet(viewsets.ModelViewSet): queryset = Publication.objects.all() serializer_class = PublicationSerializer permission_classes = [PublicPermission] class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer permission_classes = [ImagePermission] Permissions: class ImagePermission(BasePermission): edit_methods = ['PUT', 'PATCH'] def has_permission(self, request, view): if request.method in SAFE_METHODS: return True if request.user.is_authenticated: return True def has_object_permission(self, request, view, obj): if request.user.is_superuser: return True if request.method in SAFE_METHODS: return True if request.user.id == Publication.objects.get(id=obj.image_to_pub_id).pub_author_id: return True if request.user.is_staff and request.method not in self.edit_methods: return True return False class ImageAuthorPermission(BasePermission): def has_object_permission(self, request, view, obj): if request.user.id == Publication.objects.get(id=obj.image_to_pub_id).pub_author_id: return True return False Now it works as i described above. But i'm mot sure if this is good practice. I mean class <ImagePermission>. There are two times check if method in SAFE_METHODS. If i delete that check out … -
How to make my django views.py read excel sheet and display a blank cell, not "nan"
I am working on a project using django and plotly. It reads from an excel sheet and displays the data accordingly. Everything works except I have a child survey column that is only populated with some parent surveys. Because of that, the cells without a child survey are displaying 'nan' instead of just being empty. this is my function in views.py: def survey_status_view(request): # Fetch data for all CLINs and calculate necessary values clin_data = [] # Get all unique combinations of CLIN and child survey unique_clins = SurveyData.objects.values('clin', 'survey_child').distinct() for clin in unique_clins: clin_id = clin['clin'] child_survey = clin['survey_child'] # Check if the child_survey is 'None' (the string), and handle it appropriately if child_survey == 'None': child_survey = '' # Replace 'None' with an empty string # Filter by both clin and child_survey survey_data = SurveyData.objects.filter(clin=clin_id, survey_child=child_survey) # Total units for the current CLIN and child survey total_units = survey_data.first().units if survey_data.exists() else 0 # Count redeemed units based on non-null redemption dates redeemed_count = survey_data.filter(redemption_date__isnull=False).count() # Calculate funds for this CLIN and child survey total_funds = total_units * survey_data.first().denomination if total_units > 0 else 0 spent_funds = redeemed_count * survey_data.first().denomination if redeemed_count > 0 else 0 remaining_funds = … -
I have a persistent 'FOREIGN KEY CONSTRAINT failed' error with shopping cart app, is it a problem with the models?
So I'm working with a group trying to code a kind of library. We're using django to create the web application, but I keep seeing this error occur.enter image description here Here's the model I'm using in the cart app: from django.db import models from video_rental.models import Movie, CustomUser from django.conf import settings class CartItem(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.quantity} x {self.movie.title}' Here are the views: from django.shortcuts import render from django.shortcuts import render, redirect from .models import CartItem from video_rental.models import Movie def movie_list(request): movies = Movie.objects.all() return render(request, 'myapp/index.html', {'products': movies}) def view_cart(request): cart_items = CartItem.objects.filter(user=request.user) return render(request, 'myapp/cart.html', {'cart_items': cart_items}) def add_to_cart(request, title): movie= Movie.objects.get(title=title) cart_item, created = CartItem.objects.get_or_create(movie=movie, user=request.user) cart_item.quantity += 1 cart_item.save() return redirect('cart:view_cart') def remove_from_cart(request, title): cart_item = CartItem.objects.get(title=title) cart_item.delete() return redirect('cart:view_cart') def home(request): return HttpResponse('Hello, World!') This persistently happens in the admin panel when I'm trying to add things to a cart and save it. What should I do from here? Movie is defined in the video_rental app so I imported the model from there. I'm wondering what this Foreign Key error and how I can make it work. I've … -
Django+tenant FATAL: sorry, too many clients already
I am currently updating the following error in my application: FATAL: sorry, too many clients already This error does not occur all the time, only at certain times of the day. I have the following database configuration where I use tenants: DATABASE_URL = os.environ.get('DATABASE_URL') DATABASES = {'default': dj_database_url.parse(DATABASE_URL)} DATABASES['default']['ATOMIC_REQUESTS'] = True DATABASES['default']['ENGINE'] = 'django_tenants.postgresql_backend' DATABASES['default']['CONN_MAX_AGE'] = 300 DATABASES['default']['OPTIONS'] = {'MAX_CONNS': 25} DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) What I don't understand is that when I query the maximum number of connections directly in the database, the number that appears is 1708: max_connections And the error starts to pop up when my bank starts to have the number of connections above 400: dashboard Initially my backend connection to the database did not have the following settings: DATABASES\['default'\]\['CONN_MAX_AGE'\] = 300 DATABASES\['default'\]\['OPTIONS'\] = {'MAX_CONNS': 25} However, I believe that these settings would not affect the tenant. -
django-ckeditor RichTextUploadingField does not load images to s3 bucket
I try to load my images through RichTextUploadingField into the s3 bucket, but the image doesn't load: Here is my settings.py: INSTALLED_APPS = [ ... 'bootstrap4', 'imagekit', 'storages', #aws 'taggit', 'ckeditor', 'ckeditor_uploader', ... ] CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { ... } MIDDLEWARE = [ ... 'whitenoise.middleware.WhiteNoiseMiddleware' ] AWS_ACCESS_KEY_ID = var_getter('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = var_getter('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = var_getter('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_NAME = var_getter("AWS_S3_SIGNATURE_NAME") AWS_S3_REGION_NAME = var_getter("AWS_S3_REGION_NAME") AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' AWS_QUERYSTRING_AUTH = False for images from s3 # AWS_DEFAULT_ACL = None AWS_S3_VERIFY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/uploads/' MEDIA_ROOT = 'uploads/' This is my model.py from django.db import models from django.urls import reverse from taggit.managers import TaggableManager from ckeditor_uploader.fields import RichTextUploadingField from ckeditor.fields import RichTextField from imagekit.models import ImageSpecField, ProcessedImageField from imagekit.processors import ResizeToFill class Article(models.Model): """Articles under section """ STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) section = models.ForeignKey(Section, on_delete=models.CASCADE, null=False, blank=False) topic = models.CharField(max_length=200) slug = models.SlugField(unique=True, blank=False) body = RichTextUploadingField(blank=True, null=True, external_plugin_resources=[( 'youtube', '/static/youtube/youtube/', 'plugin.js', )] ) date_added = models.DateTimeField() thumb = ProcessedImageField(upload_to='thumbs_/%Y/%m/', processors=[ResizeToFill(800, 458)], blank=True, null=True, format='PNG', options={'quality': … -
Error while deploying django project to Vercel [duplicate]
I am trying to deploy a Django project to Vercel, but I am running into an issue related to distutils. During the build process, I get a ModuleNotFoundError: No module named 'distutils', and I'm unsure how to resolve this error. Below is my setup, and the build error I’m seeing. My Vercel configuration: In the vercel.json file, I am specifying the Django WSGI app as the entry point, along with Python as the runtime without specifying the version as its version 3.12 by default: { "builds": [{ "src": "trial_project_django/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python" } }], "routes": [ { "src": "/(.*)", "dest": "trial_project_django/wsgi.py" } ] } My requirements.txt file absl-py==2.1.0 aioredis==1.3.1 asgiref==3.7.2 astunparse==1.6.3 async-timeout==4.0.3 attrs==23.2.0 autobahn==23.6.2 Automat==22.10.0 cachetools==5.3.3 certifi==2024.6.2 cffi==1.16.0 channels==4.1.0 channels-redis==2.4.2 charset-normalizer==3.3.2 constantly==23.10.4 cryptography==42.0.8 daphne==4.1.2 dj-database-url==2.1.0 Django==5.0.3 django-cors-headers==4.4.0 django-heroku==0.3.1 elastic-transport==8.15.0 elasticsearch==8.15.1 elasticsearch-dsl==8.15.3 et-xmlfile==1.1.0 flatbuffers==24.3.25 gast==0.5.4 git-filter-repo==2.38.0 google-auth==2.30.0 google-auth-oauthlib==1.2.0 google-pasta==0.2.0 grpcio==1.64.1 gunicorn==22.0.0 h5py==3.11.0 hiredis==2.3.2 hyperlink==21.0.0 idna==3.7 incremental==22.10.0 joblib==1.4.2 keras==2.15.0 libclang==18.1.1 Markdown==3.6 markdown-it-py==3.0.0 MarkupSafe==2.1.5 mdurl==0.1.2 ml-dtypes==0.2.0 msgpack==0.6.2 namex==0.0.8 numpy==1.26.4 oauthlib==3.2.2 opencv-python==4.9.0.80 openpyxl==3.1.5 opt-einsum==3.3.0 optree==0.11.0 packaging==24.0 pandas==2.2.2 protobuf==4.25.3 psycopg2==2.9.9 pyasn1==0.6.0 pyasn1_modules==0.4.0 pycparser==2.22 pydub==0.25.1 Pygments==2.18.0 pykalman==0.9.7 pyOpenSSL==24.1.0 python-dateutil==2.9.0.post0 pytz==2024.1 redis==5.0.5 requests==2.32.3 requests-oauthlib==2.0.0 rich==13.7.1 rsa==4.9 scikit-learn==1.5.0 scipy==1.13.1 service-identity==24.1.0 six==1.16.0 sqlparse==0.4.4 tensorboard==2.15.2 tensorboard-data-server==0.7.2 tensorflow==2.15.0 tensorflow-estimator==2.15.0 tensorflow-intel==2.15.0 tensorflow-io-gcs-filesystem==0.31.0 termcolor==2.4.0 threadpoolctl==3.5.0 Twisted==24.3.0 twisted-iocpsupport==1.0.4 txaio==23.1.1 … -
Can not make SQL request of django field in Postgresql database
I have a django model named Interface and created in Postgresql DB? Some char fiels are stored as extended and i can SQL SELECT requests can not find those columns (error bellow). Please someone knows how to solve this ? BR, Error SELECT deviceIp FROM home_interface limit 2; ERROR: column "deviceip" does not exist LINE 1: SELECT deviceIp FROM home_interface limit 2; ^ HINT: Perhaps you meant to reference the column "home_interface.deviceIp". Models class Interface(models.Model): deviceIp = models.CharField(max_length=100) ifAlias = models.CharField(max_length=100) ifDescription = models.CharField(max_length=100) deviceName = models.CharField(max_length=100, default='') ifIndex = models.IntegerField(default=0.0) name = models.CharField(max_length=100) class Meta: ordering = ['deviceIp'] unique_together = ('deviceIp', 'ifIndex') \d+ home_interface Column | Type | Collation | Nullable | Default | Storage | Compr ession | Stats target | Description ---------------+------------------------+-----------+----------+--------------------------------------------+----------+------ -------+--------------+------------- id | integer | | not null | nextval('home_interface_id_seq'::regclass) | plain | | | deviceIp | character varying(100) | | not null | | extended | | | ifAlias | character varying(100) | | not null | | extended | | | ifDescription | character varying(100) | | not null | | extended | | | deviceName | character varying(100) | | not null | | extended | | | ifIndex | integer | … -
Why I can't install Django channels?
My OS is ubuntu 24.04. I am trying to create a chat application in Django. For that I need django channels and try to install them with pip install channels command. After executing this command I get this error: pip install channels error: externally-managed-environment × This environment is externally managed ╰─> To install Python packages system-wide, try apt install python3-xyz, where xyz is the package you are trying to install. If you wish to install a non-Debian-packaged Python package, create a virtual environment using python3 -m venv path/to/venv. Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make sure you have python3-full installed. If you wish to install a non-Debian packaged Python application, it may be easiest to use pipx install xyz, which will manage a virtual environment for you. Make sure you have pipx installed. See /usr/share/doc/python3.12/README.venv for more information. note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages. hint: See PEP 668 for the detailed specification. I just want to install with pip the django channels to use it in chat application. -
Trying to import a CSV file renders empty fields except for ID
I created import resources to import categories into the database. When I import the preview shows empty values for the name, description and parent columns and only id has a value. Here are my models: class OnlineCategory(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=500, null=True, blank=True) parent = models.ForeignKey('self', null=True, blank=True, related_name='sub_categories', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "Online category" verbose_name_plural = "Online categories" db_table = "online_categories" def __str__(self): return str(self.name) def can_be_deleted(self): return self.name != "uncategorized" def delete(self, *args, **kwargs): if self.can_be_deleted(): super().delete(*args, **kwargs) else: raise Exception("This category cannot be deleted.") def get_descendants(self): descendants = [] children = self.sub_categories.all() for child in children: descendants.append(child) descendants.extend(child.get_descendants()) return descendants class OfflineCategory(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=500, null=True, blank=True) parent = models.ForeignKey('self', null=True, blank=True, related_name='sub_categories', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "Offline category" verbose_name_plural = "Offline categories" db_table = "offline_categories" def __str__(self): return str(self.name) def can_be_deleted(self): return self.name != "uncategorized" def delete(self, *args, **kwargs): if self.can_be_deleted(): super().delete(*args, **kwargs) else: raise Exception("This category cannot be deleted.") def get_descendants(self): descendants = [] children = self.sub_categories.all() for child in children: descendants.append(child) descendants.extend(child.get_descendants()) return descendants Here is my … -
Gateway Timeout - The gateway did not receive a timely response from the upstream server or application when running under apache
My django server implements rest apies for excel operations so that user can upload/download data from/to django server's database. Those upload/download-operations take 20-50 minutes and everything works when started my django-server using manage.py runserver. But when excuted under apache those may finish for Gateway Timeout The gateway did not receive a timely response from the upstream server or application and log message: Timeout when reading response headers from daemon process 'pxpro_wsgi': /srv/django/pxpro/settings/wsgi.py. <VirtualHost *:80> ServerAdmin palvelin.hallinta@<myorg>.fi ServerName tkpyapps01p.ad.<myorg>.fi ErrorLog /var/log/httpd/pxpro-error_log CustomLog /var/log/httpd/pxpro-access_log combined LogLevel warn HostnameLookups Off UseCanonicalName Off ServerSignature Off RequestReadTimeout header=15-150,MinRate=250 body=30-3600,MinRate=150 <IfModule wsgi_module> WSGIDaemonProcess pxpro_wsgi user=django group=django home=/srv/django python-home=/srv/django/pxpro-env-3.9 python-path=/srv/django/pxpro processes=16 threads=1 maximum-requests=20000 display-name=%{GROUP} connect-timeout=1200 socket-timeout=1200 queue-timeout=1200 response-socket-timeout=1200 request-timeout=1200 inactivity-timeout=1200 header-buffer-size=1073741824 WSGIProcessGroup pxpro_wsgi WSGIApplicationGroup pxpro_wsgi WSGIScriptAlias / /srv/django/pxpro/settings/wsgi.py process-group=pxpro_wsgi application-group=pxpro_wsgi </IfModule> <Directory "/srv/django/pxpro/settings"> <Files wsgi.py> Require all granted </Files> Require all denied </Directory> <Location "/"> Options Indexes Includes FollowSymlinks </Location> </VirtualHost> How to fix ? -
Django tinymce makes all text fields a rich text editor
I am using a DRF as my backend. I configured django parler to manage my translations. I would like to use TinyMCE and normal text fields on the same admin page. This is my model: from django.db import models from parler.models import TranslatedFields, TranslatableModel, TranslatedField from django.utils.translation import gettext as _ from tinymce.models import HTMLField from core.utils import validate_image_size class SportCard(TranslatableModel): sport = models.ForeignKey('Sport', on_delete=models.CASCADE, verbose_name='Sport út') name = TranslatedField(any_language=True) image = models.ImageField(upload_to='media', validators=[validate_image_size]) description = TranslatedField(any_language=True) summary = TranslatedField(any_language=True) translations = TranslatedFields( name=models.CharField(_("name"), max_length=255), description=HTMLField(_("description")), summary=models.TextField(_("summary")), ) def __str__(self): return self.name However on the admin page the models.TextField shows as a TinyMCE: This is the config in my settings.py: TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 800, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'silver', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak …