Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelForm: how do I pre-populate data for a ModelForm overriding a field's widget? (Some working, some not.)
I have a model form with a number of fields that need to use widgets other than the default widget for the model data type. Loading the update form before adding custom widgets, all the data pre-populates for the current object correctly. As soon as I add a custom widget for any field, the pre-population for that field breaks. For example, this works as expected: class ChecklistForm(forms.ModelForm): class Meta: model = Checklist fields = [ "expected_time", #TimeField "completed", #BooleanField, nullable ] But I want control over the widgets used. I'd like the boolean completed field to render as a checkbox even though it is nullable, so I add: class ChecklistForm(forms.ModelForm): class Meta: model = Checklist fields = [ "expected_time", #TimeField "completed", #BooleanField, nullable "date", #DateField ] widgets = { 'expected_time': forms.TimeInput(format='%H:%M',attrs={'type': 'time'}), 'completed': forms.CheckboxInput(), 'date': forms.DateInput(format=('%m/%d/%Y'), attrs={'placeholder':'Select a date', 'type':'date'}), } When I load an update form, completed pre-populates correctly, while expected_time and date do not. Why? And is there a way to pre-populate these fields automatically? -
Memory never releases on Heroku, slow memory leak from models in Django?
I have been troubleshooting memory leak issues on my Django application deployed to Heroku. Basically, when the app is deployed/dyno restarted RAM hovers around 40% then as soon as someone gets on, it goes to 80% usage then stays there and never goes back down. Here is a screenshot of my last 24 hours: Things I have tried: Caching expensive things that are called often (using @cached_property), like checking a users subscription that is tied to their organization. Optimizing my queries, so far the biggest queryset I bring back is ~20 rows and isn't particularly big. Ran a memory profiler (pympler) that has a tab on Django Debug Toolbar. Admittedly am unsure of what I am looking at. Lowered gunicorn workers to 2 instead of 4 Checked that database connections weren't going haywire (currently 2 connections) Some other ideas of what it could be but unsure how to properly troubleshoot: I have middleware where I check for a subscription that runs on most pages, could this be somehow leaking/storing data? If I hit a 3rd party API (which isn't that often in this app) do I have to actively run del to get it out of memory? Has anyone else … -
How to remove `b'\x80\x05\x95\x08\...` from the contents of cache in Django?
I set 4 cache values with LocMemCache as shown below: from django.core.cache import cache cache.set("first_name", "John") cache.set("last_name", "Smith", version=2) cache.set("age", 36, version=3) cache.set("gender", "Male") Then, I tried to see the contents of the cache with cache._cache as shown below: from django.core.cache import cache print(cache._cache) # Here But, each key's value contains b'\x80\x05\x95\x08\... as shown below: OrderedDict([(':1:gender', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04Male\x94.'), (':3:age', b'\x80\x05K$.'), (':2:last_name', b'\x80\x05\x95\t\x00\x00\x00\x00\x00\x00\x00\x8c\x05Smith\x94.'), (':1:first_name', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04John\x94.')]) And, I tried to see the contents of the cache with cache._cache.items() as shown below: from django.core.cache import cache print(cache._cache.items()) # Here But again, each key's value contains b'\x80\x05\x95\x08\... as shown below: odict_items([(':1:gender', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04Male\x94.'), (':3:age', b'\x80\x05K$.'), (':2:last_name', b'\x80\x05\x95\t\x00\x00\x00\x00\x00\x00\x00\x8c\x05Smith\x94.'), (':1:first_name', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04John\x94.')]) Lastly, I tried to see the contents of the cache with locmem._caches as shown below: from django.core.cache.backends import locmem print(locmem._caches) # Here But again, each key's value contains b'\x80\x05\x95\x08\... as shown below: {'': OrderedDict([(':1:gender', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04Male\x94.'), (':3:age', b'\x80\x05K$.'), (':2:last_name', b'\x80\x05\x95\t\x00\x00\x00\x00\x00\x00\x00\x8c\x05Smith\x94.'), (':1:first_name', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04John\x94.')])} My questions: How can I remove b'\x80\x05\x95\x08\... from the contents of the cache? What is b'\x80\x05\x95\x08\...? -
Django admin: displaying computed property when viewing a single item
I store compressed strings in the database. I would like to see the actual string when in Django Admin. Since the strings are very long, I don't want them to appear in the list view, but only when viewing a single item (row). So, I can define: @property def short_my_field(self): return pickle.loads(brotly.decompress(self.my_field))[:80] @property def original_my_field(self): return pickle.loads(brotly.decompress(self.my_field)) I will then put short_my_field into list_display. But how do I cause original_my_field to display when viewing a single item? -
Got an lint error while running a dockerised project on github actions
I don't understand the error and I tried any times (https://i.stack.imgur.com/xNs3G.png) Here is my setup for github actions: --- name: Checks on: [push] jobs: test-lint: name: Test and Lint runs-on: ubuntu-20.04 steps: - name: Checkout uses: actions/checkout@v2 - name: Test run: docker-compose run --rm app sh -c "python manage.py wait_for_db && python manage.py test" - name: Lint run: docker-compose run --rm app sh -c "flake8" -
How to display the chapters of the Bible from django-bible package?
I'm trying to display the chapters of the bible from the bible package available here https://github.com/davisd/django-bible. Some of the codes are deprecated and I have refactored some. Now, I have the JSON file of the bible loaded in my database. I'm also able to display a list of the books of the Bible. The problem I'm facing is how to display the chapters of each book from my database. I have tried the following: models.py from django.db import models from .managers import BookManager class Book(models.Model): """ Book of the Bible """ number = models.PositiveIntegerField(primary_key=True, unique=True, db_index=True) slug = models.SlugField(unique=True) name = models.CharField(max_length=64, db_index=True) is_new_testament = models.BooleanField() objects = BookManager() def get_absolute_url(self): """ Returns the absolute url """ return reverse('book_detail', [self.slug,]) def __unicode__(self): return self.name class Meta: ordering = ['number',] class Chapter(models.Model): """ Chapter of the Bible """ book = models.ForeignKey(Book, related_name='chapters', on_delete=models.CASCADE) number = models.PositiveIntegerField(db_index=True) def __unicode__(self): return '%s %s' % (self.book.name, self.number) def get_next_chapter(self): try: return Chapter.objects.filter( book=self.book,number__gt=self.number).order_by( 'number')[0] except IndexError: return None def get_previous_chapter(self): try: return Chapter.objects.filter( book=self.book,number__lt=self.number).order_by( '-number')[0] except IndexError: return None def get_absolute_url(self): """ Returns the absolute url """ return reverse('chapter_detail', [self.book.slug, self.number]) class Meta: ordering = ['number',] unique_together=(('book','number',),) views.py from django.http import HttpResponse, Http404 from … -
Python Libraries (Twisted, regex, cryptography, hiredis)
These are all the libraries I used in my project. aioredis==1.3.1 alabaster==0.7.12 amqp==2.6.0 appdirs==1.4.4 Arpeggio==1.9.2 asgi-redis==1.4.3 asgiref==3.2.7 async-timeout==3.0.1 atomicwrites==1.4.1 attrs==19.3.0 autobahn==20.4.3 autoflake==1.3.1 Automat==20.2.0 autopep8==1.5.2 Babel==2.8.0 backcall==0.2.0 backports.shutil-get-terminal-size==1.0.0 bandit==1.6.2 billiard==3.6.3.0 black==19.10b0 bleach==3.1.5 boto3==1.17.0 botocore==1.20.0 bumpversion==0.5.3 celery==4.4.5 certifi==2020.4.5.2 cffi==1.15.1 channels==2.4.0 channels-redis==2.4.2 chardet==3.0.4 Click==7.0 colorama==0.4.6 colour==0.1.5 constantly==15.1.0 coverage==5.0.3 coveralls==1.10.0 cryptography==41.0.3 daphne==2.5.0 decorator==4.4.2 distlib==0.3.0 Django==3.0.7 django-admin-inline-paginator==0.3.0 django-admin-logs==1.0.1 django-admin-sortable2==0.7.6 django-ckeditor==5.9.0 django-cors-headers==3.11.0 django-debug-toolbar==2.2 django-dotenv==1.4.2 django-environ==0.4.5 django-fernet-fields==0.6 django-impersonate==1.9.1 django-js-asset==1.2.2 django-mapper==1.1.11 django-modelclone==0.7.1 django-mysql==3.7.1 django-pagination-bootstrap==2.3.0 django-redis==5.2.0 django-safedelete==1.0.0 django-silk==4.1.0 django-slack==5.17.6 django-solo==1.1.3 django-storages==1.11.1 djangorestframework==3.12.1 doc8==0.8.0 docopt==0.6.2 docutils==0.15.2 docxcompose==1.4.0 docxtpl==0.16.5 EasyProcess==0.3 entrypoint2==0.2.1 entrypoints==0.3 enum34==1.1.10 et-xmlfile==1.0.1 filelock==3.0.12 flake8==3.7.9 flake8-2020==1.5.0 flake8-bandit==2.1.2 flake8-broken-line==0.1.1 flake8-bugbear==20.1.4 flake8-builtins==1.4.2 flake8-comprehensions==3.2.2 flake8-debugger==3.2.1 flake8-fixme==1.1.1 flake8-isort==2.8.0 flake8-logging-format==0.6.0 flake8-mutable==1.2.0 flake8-polyfill==1.0.2 flake8-variables-names==0.0.3 flower==0.9.7 future==0.18.2 gitdb==4.0.5 GitPython==3.1.3 gprof2dot==2019.11.30 gunicorn==20.0.4 hiredis==2.2.3 humanize==3.9.0 hyperlink==19.0.0 idna==2.9 imagesize==1.2.0 importlib-metadata==1.6.1 incremental==17.5.0 ipython==7.15.0 ipython-genutils==0.2.0 isort==4.3.21 jdcal==1.4.1 jedi==0.17.0 jeepney==0.4.3 Jinja2==2.11.2 jmespath==0.10.0 keyring==21.2.1 kombu==4.6.10 lxml==4.9.3 MarkupSafe==1.1.1 mccabe==0.6.1 more-itertools==8.3.0 msgpack==0.6.2 msgpack-python==0.5.6 numpy==1.23.5 olefile==0.46 openpyxl==3.0.4 packaging==20.4 pandas==1.5.2 parso==0.7.0 pathlib2==2.3.5 pathspec==0.8.0 pbr==5.4.5 pep8-naming==0.9.1 pexpect==4.8.0 pickleshare==0.7.5 Pillow==9.4.0 pillow-heif==0.13.0 pkginfo==1.5.0.1 platformdirs==3.10.0 pluggy==0.13.1 prometheus-client==0.8.0 prompt-toolkit==3.0.5 ptyprocess==0.6.0 py==1.8.1 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.5.0 pycparser==2.20 pydocstyle==5.0.2 pyflakes==2.1.1 Pygments==2.6.1 PyHamcrest==2.0.2 pyOpenSSL==19.1.0 pyparsing==2.4.7 pypdf2==3.0.1 pytest==5.3.5 pytest-cov==2.8.1 pytest-runner==5.2 python-dateutil==2.8.1 python-dev-tools==2020.2.5 python-docx==0.8.11 pytz==2020.1 pyunpack==0.2.1 pyupgrade==1.26.2 pywin32-ctypes==0.2.2 PyYAML==5.3.1 readme-renderer==26.0 redis==2.10.6 regex==2023.8.8 requests==2.23.0 requests-toolbelt==0.9.1 restructuredtext-lint==1.3.1 s3transfer==0.3.4 scandir==1.10.0 SecretStorage==3.1.2 sentry-sdk==0.17.0 service-identity==18.1.0 simplegeneric==0.8.1 six==1.16.0 smmap==3.0.4 snowballstemmer==2.0.0 Sphinx==2.3.1 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==1.0.3 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.4 sqlparse==0.3.1 stevedore==2.0.0 testfixtures==6.14.1 textX==2.1.0 tokenize-rt==4.0.0 toml==0.10.1 tornado==6.1 tox==3.14.3 … -
How to notify a User whenever an object is Created in Django model
I would like to tell a user automatically whenever a new game or a movie is uploaded or published on the website. below is my models. #games model GAME_TYPE=( ("action", "action"), ("adventure", "adventure"), ("racing", "racing"), ("puzzle", "puzzle"), ) MOV_TYPE=( ("action", "action"), ("adventure", "adventure"), ("sci-fi", "sci-fi"), ("horror", "horror"), ("drama", "drama"), ) GAME_OS=( ("Windows", "Windows"), ("Android", "Android"), ) class Games(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=GAME_TYPE) os=models.CharField(max_length=15, choices=GAME_OS) img=models.ImageField() developer=models.CharField(max_length=50) version=models.CharField(max_length=10) ratings=models.CharField(max_length=10) description=models.TextField() def __str__(self) -> str: return self.name class Movies(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=MOV_TYPE) description=models.TextField() released=models.DateField() def __str__(self) -> str: return self.name I need direct me on how to create an function to send or notify a user automatically whenever a game is published but l don't know how to do it. Anyone to solve me -
Django ORM Foreign Key Values how to return as single dictionary
How do I return all foreign key values into a single dict in the Django ORM? I understand how to access these values in Python, but I'm looking to retrieve them from a dict, rather than a class. class ChildModel(models.Model): location = models.TextField() class MasterModel(models.Model): town = models.ForeignKey(ChildModel, on_delete=models.CASCADE) To access the location in Python: queryset[0].town.location Accessing the values themselves does not return the location field. queryset.values() = {town: 1} What I want is: queryset.values() = {town: 1, location: some_value} If I run the SQL query in Postgres I get the dict I'm looking for (all inner join fields returned as a single dict). But how to do this in Django? -
Is there is option to cast django subquery object values to one text field
I have ticketing system, and for table view I'm using DataTables, I'm passing queryset values to DT constructor and rendering table view, this provides fast table data filtering and search options data = TicketData.objects.filter(f).values(...) json_data = repr(json.dumps(list(data), default=str)) TicketData object with related fields is big, I can't display all object values in table row, but I'm using them for filtering and search by putting them in hidden block. Each ticket can hold multiple assets and I need to have possibility to search/filter data in table by specific asset values, currently I'm adding them by looping trough all related assets and setting necessary values as new text field for object: for ticket in data: asset_search_data= "" for asset in TicketAssetMap.objects.filter(ticket__id=ticket['id'], edited=True): asset_search_data += str(asset.asset.asset_nr) + " " + str(asset.asset.inventory_nr)+ " " + str(asset.asset.room) + " " ticket['asset_search_data'] = asset_search_data json_data = repr(json.dumps(list(data), default=str)) This approach works, but page load is slow due to many sql requests. I'm thinking to use subquery for main data query, but I cant figure out how to combine queryset in to one text field. asset_data = TicketAssetMap.objects.filter(ticket=OuterRef('pk')).annotate(assets=Concat("asset__asset_nr", Value(" "), "asset__room", Value(" "), output_field=TextField())).values('assets') data = TicketData.objects.filter(f).annotate(assets=Subquery(asset_data)) This will fail as soon as ticket will have more … -
Configure django-tenants to write and read from AzureStorage
As per the django-tenants docs for file handling. I've done everything but if i include this line. DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" This will use local file storage path for storage. And when i checked TenantFileSystemStorage this class is inherited from FileSystemStorage. How can i configue TenantFileSystemStorage to use AzureStorage? I don't think any docs available to achieve this. Any help on this is much appreciated. Requirements: Upload should save any file to azure and also read from azure. -
Anyone to help me on how to create an automatic notification system that sends a message to a User whenever an object is created or modified
I have three models below, but l like to create a Notification System to send a message to a User whenever ; An object is created in all those models An object is modified in all those models And l would like to add trick that it sends the Notification Message after 15 minutes of publiction or creation. And I would like to pass the following data if available in the object ; the Name of the Object, the Image of the Object, and the type of the Object. My views from django.shortcuts import render def auto_notification(request): return render (request, "user/dashboard.html") My models from django.db import models from django.contrib.auth.models import User #articles model class Articles(models.Model): title = models.CharField(max_length=300) date= models.DateField() author=models.ForeignKey(User, on_delete=models.CASCADE) body=models.TextField() def __str__(self) -> str: return self.title #games model GAME_TYPE=( ("action", "action"), ("adventure", "adventure"), ("racing", "racing"), ("puzzle", "puzzle"), ) MOV_TYPE=( ("action", "action"), ("adventure", "adventure"), ("sci-fi", "sci-fi"), ("horror", "horror"), ("drama", "drama"), ) GAME_OS=( ("Windows", "Windows"), ("Android", "Android"), ) class Games(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=GAME_TYPE) os=models.CharField(max_length=15, choices=GAME_OS) img=models.ImageField() developer=models.CharField(max_length=50) version=models.CharField(max_length=10) ratings=models.CharField(max_length=10) description=models.TextField() def __str__(self) -> str: return self.name class Movies(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=MOV_TYPE) description=models.TextField() released=models.DateField() def __str__(self) -> str: return self.name Lastly I would like to add a : Notification DELETE … -
Where can i find out Python based MCQs and Answers. Please suggest some good references
I am building a Question Bank Model. I need Sample Python based MCQs and Answers to refer as my training data. Please suggest some references I am trying every where and no luck yet. Can one help me with a valid reference to sample Python MCQs covering basics, advanced, data science, AIML Django, Flask. Any great reference will do a great help to me -
How to create a ldap BIND_DN for samba active directory
I am trying to setup samba active directory users authentication for my Django app. I working in linux. I don't have access to windows active directory. I got a docker image smblds for samba AD DC on Ubuntu 22.04 using docker run --name smblds \ --publish 389:389 \ --publish 636:636 \ --detach smblds/smblds:latest The docker started fine. I can see the smb.conf and other tdb files created. But this docker does not set the BIND_DN value. So, I executed the docker and from inside the smblds docker I provisioned the active directory with samba-tool domain provision --use-rfc2307 --interactive I used all the default settings for Realm, Domain, server role, dns backend and Administrator password I see following messages in the output Setting up self join Repacking database from v1 to v2 format (first record CN=ms-WMI-StringSetParam,CN=Schema,CN=Configuration,DC=samdom,DC=example,DC=com) Repack: re-packed 10000 records so far Repacking database from v1 to v2 format (first record CN=server-Display,CN=409,CN=DisplaySpecifiers,CN=Configuration,DC=samdom,DC=example,DC=com) Repacking database from v1 to v2 format (first record CN=51cba88b-99cf-4e16-bef2-c427b38d0767,CN=Operations,CN=DomainUpdates,CN=System,DC=samdom,DC=example,DC=com) Is any of these a BIND_DN. Actually when I try to connect to active directory using python ldap I see invalid credential error. >>> import ldap >>> ldap_server = ldap.initialize("ldap://172.17.0.5/") >>> ldap_server.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) >>> ldap_server.set_option(ldap.OPT_X_TLS_NEWCTX, 0) >>> ldap_server.start_tls_s() >>> … -
Django - pythonanywhere - ProxyConnectionError
I deployed my Django project on pythonanywhere. In the project, I use "storages.backends.s3boto3.S3Boto3Storage" as DEFAULT_FILE_STORAGE. It connects to a cloud storage so that I can upload and save media files on there. It works fine on my local system but on pythonanywhere, it gives this error when a media file is going to be uploaded: ProxyConnectionError Failed to connect to proxy URL: "http://proxy.server:3128" I'm new to this and I don't know what else information is needed on this for someone to answer my question. So let me know to edit my question. -
Testing LDAP authentication in Django
I followed the answer in this question Testing authentication in Django but no one said the result for a successful connection. I copied the same code and got a response which I do not know. Here is the response: Does anyone know what it means? -
Django Multipart Upload with Ajax AWS S3 | How to get presigned URL?
Brother, i cant get it... so i have this: s3fileuploader.py import boto3 from boto3.s3.transfer import TransferConfig from .progresshandler import ProgressHandler from lumen import settings class S3Uploader(object): def __init__(self): self.s3 = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) self.config = TransferConfig( multipart_threshold=1024 * 100, max_concurrency=1, multipart_chunksize=1024 * 100, use_threads=False ) self.folder_name = 'simple_file_upload' self.progress_handler = None def upload(self, file_obj, filename, file_type, file_size): self.progress_handler = ProgressHandler(self.folder_name, filename, file_size) self.s3.upload_fileobj(file_obj, settings.AWS_STORAGE_BUCKET_NAME, # settings.AWS_S3_REGION_NAME, f'{self.folder_name}/{filename}', ExtraArgs={'ContentType': file_type}, Config=self.config, Callback=self.progress_handler) def get_upload_status(self): if self.progress_handler: return self.progress_handler.get_upload_status() return None class S3ParallelMultipartUploader(S3Uploader): def __init__(self): super(S3ParallelMultipartUploader, self).__init__() self.config = TransferConfig( multipart_threshold=1024 * 100, max_concurrency=10, multipart_chunksize=1024 * 100, use_threads=True ) self.folder_name = 'multipart_upload' progresshandler.py import threading from time import perf_counter from django.core.cache import cache class ProgressHandler(object): def __init__(self, cache_key_prefix, filename, size): self._filename = filename self._size = size self.perf_counter_start = perf_counter() self.cache_key = f'{cache_key_prefix}_{self._filename}' cache.set(self.cache_key, { 'uploaded_size': 0, 'progress_perc': 0, 'time_taken_s': 0 }) self._lock = threading.Lock() def __call__(self, bytes_amount): with self._lock: upload_status = cache.get(self.cache_key) upload_status['uploaded_size'] += bytes_amount upload_status['progress_perc'] = int((upload_status['uploaded_size'] / self._size) * 100) upload_status['time_taken_s'] = perf_counter() - self.perf_counter_start cache.set(self.cache_key, upload_status) def get_upload_status(self): upload_status = cache.get(self.cache_key) if upload_status: return {'progress_perc': upload_status['progress_perc'], 'time_taken_s': round(upload_status['time_taken_s'], 2)} return {'progress_perc': 0, 'time_taken_s': 0} views.py s3uploader = S3ParallelMultipartUploader() def create_post_aws(request): if request.method == 'POST': file = request.FILES["file"] title … -
How to setup Keycloak client for Frontend?
I have included the DRF-Social-OAuth2 library and set up the Keycloak client for the Backend. Now I have to create a new public client for Frontend? If yes, what is the right way to do it? -
Issue with django channels `ValueError: Invalid IPv6 URL`
I’ve setup django channels in my project and other things like APIs and Other admin urls are working fine, but when I try to create a socket connection in my project I’m getting this error WebSocket HANDSHAKING /ws/notification/ [127.0.0.1:48494] Exception inside application: Invalid IPv6 URL Traceback (most recent call last): File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 35, in __call__ if self.valid_origin(parsed_origin): File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 54, in valid_origin return self.validate_origin(parsed_origin) File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 73, in validate_origin return any( File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 74, in <genexpr> pattern == "*" or self.match_allowed_origin(parsed_origin, pattern) File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 102, in match_allowed_origin pattern_hostname = urlparse("//" + pattern).hostname or pattern File "/usr/lib/python3.10/urllib/parse.py", line 400, in urlparse splitresult = urlsplit(url, scheme, allow_fragments) File "/usr/lib/python3.10/urllib/parse.py", line 495, in urlsplit raise ValueError("Invalid IPv6 URL") ValueError: Invalid IPv6 URL WebSocket DISCONNECT /ws/notification/ [127.0.0.1:48494] Can anyone help me with this one. -
How to create qr code from url in django? Calling from another function
I wanted to write a function that takes the generated url for each device and converts it to a qr code. this function should be called in add_new_device after url is created. My code is like this, it's not adding device at the moment. def add_new_device(self, request): user = User.objects.get(username=request.data["username"]) # last num of device to add in device_id last_number = len(Device.objects.all()) device = Device() device = self.write_fields_to_object(device, request.data, user) device.device_id = self.random_string_generator() + \ '-' + str(int(last_number) + 1) device.save() # Creates new station data added for the device self.set_station_data(request.data, device) if device.VMIscreen == "true": # Creates VMI screen automatically for url self.auto_create_new_layout(request, device) else: # Creates epmtpy screen for url empty_layout = Layout() self.create_url(empty_layout, device) self.create_qr(device) # Create Event object self.create_notification( user, device, "add", "device", "has added new Device") return "ok" def create_qr(self, device): qr_content = device.screen_url qr_name = f'qr_{device.device_id}.png' qr = make(qr_content) qr.save('media/' + qr_name) def create_url(self, layout, device): screen_url = base_screen_url + device.device_id + ".html" Device.objects.filter(device_id=device.device_id).update( screen_url=screen_url) html = self.edit_device_url_html(layout, device) s3.put_object(Bucket=device_url_bucket, Key=str(device.device_id) + ".html", Body=html, ACL='public-read', ContentType='text/html', CacheControl='no-cache, no-store, must-revalidate') -
Apache2 Django - Remote MySQL/MongoDB Access Denied 1045 (28000)
Im having troubles to access from a Ubuntu Server using Apache2 to a remote MongoDB database with python-mysql-connector. [wsgi:error] [pid 143490:tid 140602848225021] [remote 10.242.2.3:62831] 1045 (28000): Access denied for user 'db-mycon-read'@'176.69.189.21' (using password: YES) Apache2 .conf: <VirtualHost *:80> ... WSGIDaemonProcess Kompetenzauswertung python-path=/home/mycadmin/Kompetenzauswertung python-home=/home/mycadmin/Kompetenzauswertung/venv WSGIProcessGroup Kompetenzauswertung WSGIScriptAlias / /home/mycadmin/Kompetenzauswertung/Kompetenzauswertung/wsgi.py ... </VirtualHost> What works: connecting on local machine connecting via commandline on Ubuntu Server connecting via python-mysql-Connector using a simple python script What doesnt work: connecting via apache2 service Other Information: Django Runs a website that needs to fetch data from a remote db (Website has no ssl cert bc) -
In Django I can't populate a dropdown with variables in the for loop. The dropdown remains empty
I'm new to Django. I can't see items in a dropdown, but I can't figure out why. The dropdown remains empty. I know I might as well not be using the for loop, but I would like to use it. What am I doing wrong? I'm also using a list for x and y, so the loop can loop through the html, but it doesn't work views.py def seleziona_soggetto(request): #Match trip = Full_Record.objects.get(id=request.session.get("selected_trip_id")) partita = f"{trip.team_home}-{trip.team_away}" #Split Match x,y = partita.split('-') options = [x, y] return render(request, 'seleziona_soggetto.html', {"options": options}) seleziona_soggetto.html <select name="seleziona_soggetto" id="id_seleziona_soggetto" style="width:200px;" hx-get="{% url 'seleziona_soggetto' %}" hx-indicator=".htmx-indicator" hx-trigger="change" hx-swap="none"> <option value="">Please select</option> {% for i in options %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.trip_selector, name="trip_selector"), path('trips', views.trips, name='trips'), path('result', views.result, name='result'), path('seleziona_soggetto', views.seleziona_soggetto, name='seleziona_soggetto'), ] -
Why use One-To-One instead of inherit User class in Django?
So I want to be able to have Organizations and Customers which are users, which have some specific attributes. Everywhere I see, they use One-To-One mapping to the User class like this: class Organization(models.Model): user=models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True) tenant=models.ForeignKey(Tenant, on_delete=models.PROTECT) organization_name=models.CharField(max_length=100, default="No Organization name set") phone_number=models.PositiveBigIntegerField(default=None) description=models.TextField(max_length=None, default="No Description set") is_terms_and_conditions_agreed=models.BooleanField(default=False) status=models.IntegerField(choices=status_choices, default= PENDING) which works fine for me, but this works as well: class Organization(User): tenant=models.ForeignKey(Tenant, on_delete=models.PROTECT) organization_name=models.CharField(max_length=100) alt_number=models.PositiveBigIntegerField() description=models.TextField(max_length=None) is_terms_and_conditions_agreed=models.BooleanField(default=False) status=models.IntegerField(choices=status_choices, default= PENDING) But I cannot find a reference for inheriting User class this way without making it a proxy and making a manager. So my question is, why do we prefer the One-To-One method? -
how to get parent object from child object in Django?
class Offer(models.Model): opportunity = models.ForeignKey(Opportunity, on_delete=models.CASCADE) status = models.CharField() class Opportunity(models.Model): ...some code now i want to access offer from opportunity (child to parent). something like opportunity.offer.status. i have tried this but it doesn't work. Help please thanks. -
How can I give different priorities to flask web-apps?
My Ubuntu server runs several applications built in Python (Django or Flask), and deployed using gunicorn. Some of them also use nginx. I would like to give some of these applications a higher priority, so that, if a prioritized application is used, its performance will not be hurt by non-prioritized applications used at the same time. I know the Unix command nice could be used for giving different priorities to processes, but I do not know where exactly to apply this command: to the Python app? to the gunicorn command line? to nginx?