Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Recommend a Tech Stack for a small CRM/Inventory web/mobile app with DB access and local logins
I have some Python experience with building machine learning models in Jupyter, but I am looking to build a web app with locally created logins but all these new tech stacks are a bit overwhelming. I want to learn full stack, but which route I need to choose now. As I understand Node.js has it's route and then you now also have FastHTML, Flask DJANGO etc, and then DB's to use. I need some guidance for a novice to start learning a tech stack. And then do you mostly stick with what you start with or is it a mix-match. Yes, I understand there is no perfect formula but this is why I am asking experts in the field with years experience and not GPT. Guidance pls !!PLEASE I DO NOT WANT AN ANSWER GENERATED BY ANY LLM, HAVE READ THEM ALREADY. GOOD OLD FASHIONED EXPERIENCE PLEASE!! -
Updating multiple nested Objects in DRF
I have three linked models with many To many field relationship. I have no ideia how can i update all instances at once. I would like create three separated serializers, that could update the three instances. class PlannedChargePriceSerializer(serializers.ModelSerializer): class Meta: model = ChargePrice fields = ['id', 'start', 'end', 'price'] class PlannedChargeSerializer(serializers.ModelSerializer): prices = PlannedChargePriceSerializer(many=True) class Meta: model = Charge fields = ['id', 'type', 'qtd', 'status', 'prices'] class PlannedSerializer(serializers.ModelSerializer): charges = PlannedChargeSerializer(many=True) class Meta: model = Planned fields = '__all__' read_only_fields = ['id', 'date', 'charges'] def create(self, validated_data): charges_data = validated_data.pop('charges') planned = Planned.objects.create(**validated_data) for charge_data in charges_data: charge_prices_data = charge_data.pop('prices') charge = Charge.objects.create(planned=planned, **charge_data) for charge_price_data in charge_prices_data: ChargePrice.objects.create(charge=charge, **charge_price_data) return planned def update(self, instance, validated_data): # No idea how update multiple nested objects return instance -
Database Connections spiking randomly
I have an application with Django as backend. It is hosted on the EC2. The database is hosted on the AWS RDS Postgres SQL. The Connections to the database keep spiking to the maximum limit, even though we do not have that much users. The application is used by merely 10 people in the organization but the connections spike up to 80. Can anyone suggest what can be the issue behind this? I think it might be causing due to multiple requests from a single client leading to multiple connections. It will be great if somebody can help me out t find the cause. I tried redeploying the server as well as rebooting the rds instance but there is no change. I even tried adding the idle connection termination parameter through the rds parameter groups. When I checked the db for connection details, I saw multiple connections from same user ids. Can this be related to the issue? -
i can not install django framework on my pc. it showing " C:\Users\HomePC\AppData\Local\Programs\Python\Python312\python.exe: No module named pip"
i cannot not install django frame work on my pc it showing " i have modify my python to latest version and still showing that -
Making instances of Django records with a through model
Let's say you have a concept of a Battle, and in that battle there are Players and Enemies. The players are a simple ManyToMany, but Enemies require a Through model, because if there's a DB entry for "Goblin", players need to fight an INSTANCE of the Goblin model. Players may fight many Goblins, and each needs their own health/status at any given moment. So far, I've got a Django model like so (I'm simplifying the code for readability, and to focus on the main issue) class Battle(models.Model): players = ManyToMany(Player) enemies = ManyToMany(Enemy, through=EnemyThroughModel) With the appropriate adjustments to admin.py and such, this works in that I can attach multiple Enemies to a Battle and see them listed separately in admin, HOWEVER, those are all keyed to the same basic Enemy, and if I change one of them (say, they take damage), ALL the keyed references to that enemy now have their health reduced. Is there a neat way I can use through models to create a new instance of the enemies, so that they have independent health/mana/etc? -
VSCode not discovering pytests for Django Project
I am new to Pytest & Django, so all feedback and improvements are welcome. I am trying to use VSCode's testing sidebar with my Django Project, but it is unable to find the pytest files. Here are the commands I've run to create this example project: django-admin startproject LearningPytest pip install django-pytest Then I've created two files: pytest.ini and basic_tests.py, so my folder structure is as follows. DjangoPyTesting/ └───LearningPytest/ ├───LearningPytest/ │ ├───__init__.py │ ├───asgi.py │ ├───basic_tests.py │ ├───settings.py │ ├───urls.py │ ├───wsgi.py ├───manage.py └───pytest.ini pytest.ini [pytest] DJANGO_SETTINGS_MODULE = LearningPytest.settings python_files = tests.py test_*.py *_tests.py python_classes = Test* python_functions = test_* basic_tests.py class TestBasicMath: def setup_method(self, method): self.x = 2 self.y = 3 def test_addition(self): assert self.x + self.y == 5 def test_subtraction(self): assert self.y - self.x == 1 def test_multiplication(self): assert self.x * self.y == 6 Here is the problem, I want to use VSCode's sidebar to run my tests, but it cannot find them. This confuses me, because within my project if I run the following command: DjangoPytesting\LearningPytest>pytest it works successfully platform win32 -- Python 3.11.5, pytest-7.4.4, pluggy-1.3.0 rootdir: C:\Users\{me}\Desktop\DjangoPytesting\LearningPytest configfile: pytest.ini plugins: anyio-4.3.0, django-4.9.0 collected 3 items LearningPytest\basic_tests.py ...platform win32 -- Python 3.11.5, pytest-7.4.4, pluggy-1.3.0 rootdir: C:\Users\{me}\Desktop\DjangoPytesting\LearningPytest configfile: … -
Django backend user registration
I'm currently writing a system with users creation process involved. The system will have a 'site-administrator' who can create (and modify, delete) users. However, I'm stuck with the part of creating users. What I want is: Site Administrator creates a user Django will create a one time password and send this to the user (based on email) User logs in System detects it's the first time and forces the user (via frontend) to update password User updates password and logs in with new credentials Bearer tokens (access / refresh) are issued The frontend is VUE (with axios, pinia etc) but that's of no use for this question. The backend is Django, Djano Rest Framework, SimpleJWT and a MariaDB for storing info on the backend. Thank you for taking the time to answer this question. -
django stops running when i send an request to api
In the rest api I have a view that sends an otp sms to the user's phone . when I send a request to my api , It just sends another request to other server and waits for the response But It takes a while and django just stops working . I am worry about it . what if upload it to server and django can't handle multi requests and crashes in the real server with different request from multiple users? How can I fix this problem ? Also mu CPU has only 2 cores and I don't think using multi threading is an good idea! -
Automatically starting task queue for django-background-tasks
I'm building an application which involves a task queue from django-background-tasks. The issue that I'm facing is that I can't seem to start the queue automatically and have to manually run process_tasks in my application container. I've already tried running the process_tasks command within my Dockerfile, however this seems to not do anything as open tasks are not resolved. CMD ["bash", "-c", "python manage.py runserver 0.0.0.0:8000 && python manage.py process_tasks"] Has anyone experienced this issue, and if so how did you handle it? I tried to run the process_tasks command in my Dockerfile after executing runserver , I expected this to automatically start the task queue, however this did not yield any result.