Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django: Dynamic form doesn't correctly handle boolean inputs
This is a small form I have and dynamically construct: class AddonForm(Form): def __init__(self, addons, *args, **kwargs): super().__init__(self, *args, **kwargs) self.addons = {str(addon.pk): addon for addon in addons} for pk, addon in self.addons.items(): self.fields[str(pk)] = BooleanField(required=False, label=f"{addon} (x{addon.price_multiplier})") This is how I use it: form = AddonForm(ItemAddonTemplate.objects.filter(item=item_template_id), request.POST) if form.is_valid(): addons = form.cleaned_data This is the request.POST: <QueryDict: {'csrfmiddlewaretoken': ['cJS1fhGY3WqIflynGbZIh9TiRj8F9HjgoLOUL6TwWY4j4cotALGHpFDyQwjLiLMW'], '3': ['on'], '32': ['on']}> but when I print addons I see this: {'3': False, '30': False, '31': False, '32': False, '33': False, '34': False} 3 and 32 should be True. This is Django 5.1 and Python 3.12. -
What exactly are Django Widgets?
I am a little confused as to what exactly Django Widgets are. From https://docs.djangoproject.com/en/5.1/ref/forms/widgets/: The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget." What exactly is meant by extraction of data from GET/POST dict? That is done by the passing data argument to form instantiation, how does Widget come into picture here? If I understood correctly, Widgets just create the HTML <input> tags, and take attr parameters that set attributes of this input tag, viz. size (in case of text input), required (override on the field required value), class, etc. So how exactly do packages like crispy-forms+crispy-bootstrap5, django-bootstrap5 differ from these Widgets? And what do they do with Django Widgets? Also, these packages have parameters when rendering a field where css_class (the actual class of the input) can be modified. How does this play with Widget attr['class']? Does Django have templates for each Widget in files (like rest of the templates in the Django template system)? -
How to remove a field that was added by mistake from a form in Django
I have 3 password fields. The first one (password) is useless, it doesn't do anything literally. password1 and password2 are the real fields that are working.problem I was trying to change password and password2 ---> password and confirm password. But it didn't work, so I returned it back to password and password2, but it did this and I can't remove the extra password field that appeared there. I deleted the sql file and the migrations file and make migrations from the beginning and it didn't work.code -
How do password managers store passwords which can be shown in plain text in ui
So, I am building a password manager like Bitwarden. I have come to a point where I need to store passwords which the user provides and then later show the user the password in plain text obviously. Now my question is that how can I store passwords carefully without hashing otherwise they wont be in plain text next time the user wants it? I am building an API in Django https://github.com/Abled-Taha/apm-server -
Django Forms initials not working for some fields?
Something weird is happening. I am trying to get initial fields into my form but only some of then are filled. The address, latitude and longitude wont. this is my form: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['first_name', 'last_name', 'cpf', 'phone', 'email', 'address', 'street_name', 'street_number', 'address_complement', 'country', 'state', 'city', 'pin_code', 'latitude', 'longitude',] This is my view: default_values = { 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'cpf': request.user.cpf, 'phone': request.user.phone_number, 'email': request.user.email, 'address': checkout_address.address, 'street_name': checkout_address.street_name, 'street_number': checkout_address.street_number, 'address_complement': checkout_address.address_complement, 'country': checkout_address.country, 'state': checkout_address.state, 'city': checkout_address.city, 'pin_code': checkout_address.pin_code, 'latitude': checkout_address.latitude, 'longitude': checkout_address.longitude } form = OrderForm(initial=default_values) When I print the default_values I got all right: {'first_name': 'Admin', 'last_name': 'Sistemas', 'cpf': '9999999', 'phone': '98989898', 'email': 'rm@rm.com', 'address': 'Rua dos Lamentos, 10, Armação dos Búzios - RJ', 'street_name': 'R. dos Lamentos', 'street_number': '10', 'address_complement': 'ap32', 'country': 'Brasil', 'state': 'Rio de Janeiro', 'city': 'Armação dos Búzios', 'pin_code': '28950-000', 'latitude': '-22.7980796', 'longitude': '-41.9321335'} But by some how those three fields are not filed: Does someone could give me a tip on what the wack is going on? I tried to take some fields out and in but those three fields wont appear! Thank you very much for any help!