Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is too slow when processing exception
The view where the exception happens is processing a big dictionary with about ~350K entries. The exception is a KeyError. From what I can see from the CProfile logs, Django is trying to iterate the dictionary to get traceback data. This is simplified code from the view: @login_required def export_plan_data(request): try: form = PortfolioPlanningForm(request.GET, user=request.user) file = get_export_file(user=request.user, form.get_params()) # This is where the exception happens filename = f"Plan {timezone.now().strftime('%Y-%m-%d %H:%M:%S')}.xlsx" response = HttpResponse(file, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response["Content-Disposition"] = f"attachment; filename={filename}" return response except Exception as e: return JsonResponse({"error": "An error occurred while exporting the data"}, status=500) If I surround the entire view in a try/except block and return my custom response when an exception occurs it returns in about 10 seconds, but if I remove the try/except block and let Django handle the exception it takes about 5 minutes. Here's the Cprofile dump: 292357310 function calls (260422005 primitive calls) in 247.585 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 247.585 247.585 /usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py:44(inner) 1 0.000 0.000 241.196 241.196 /usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py:54(response_for_exception) 1 0.000 0.000 241.194 241.194 /usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py:140(handle_uncaught_exception) 1 0.000 0.000 241.194 241.194 /usr/local/lib/python3.9/site-packages/django/views/debug.py:50(technical_500_response) 1 0.000 0.000 241.192 241.192 /usr/local/lib/python3.9/site-packages/django/views/debug.py:341(get_traceback_html) 429 0.001 0.000 241.047 0.562 /usr/local/lib/python3.9/site-packages/django/template/defaultfilters.py:916(pprint) 429 0.001 0.000 … -
Why does Django require javascript to be linked in the head instead of the end of the body?
I had to do a few extended templates in django. For simplicity let's call them base.html, blog_base.html, and blog.html. (blog extends blog_base, blog_base extends base). I have a few javascript files in base.html, which worked fine in blog_base.html, but when blog.html was loaded, no GET request was ever sent to retrieve the files. I found that the only location for the tags that worked were in the section of base.html. This is odd to me because not a single other location I put these (even in blog.html) was able to load the static files. Is this a django problem or a javascript? -
Weblate Import initial data via database or rest api
Does anybody have an idea how to import translation units into Weblate? I wanted to add them via the database, but I can't create the id_hash. Using the REST API is too slow for my amount of data. It's for a single import just the initial data. -
Migrating from python 2.7 and Django 1.9 to the latest
What are the best ways to migrate from python2.7 and Django 1.9. The project is hosted in AWS and it uses the s3 for content delivery so a lot of packages for that also exists. Did create an env for python3 and installed the latest version of Django and try to start the project which went from 1 problem to another while solving each. -
ModuleNotFoundError: No module named , for python django
What's the problem ? enter image description here enter image description here It must be correct according to the folder path. It sees the path when completing it automatically, but it gives an error.Whats the problem completely. -
issue with django show image tried many ways to solve
template doest not show images i use <img src="/static/logo_coorg.png" width="60" height="40"> and settings like : BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__)) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = 'static/' by this way one of my django website does not have any issue. but another new django website is really a desparate one with this error. i am trying to fix this since last 24+ hours. help is sought. -
django strange behavior with url with slug and /
I am encountering a strange django behavior that I don't see where it could go wrong. I have the start of an app that returns dynamic pages whose url is created through the slug. Everything works well. With any slug I try it works perfectly and the urls find their path without problem. They all go through the same path. But there is ONLY one slug that does not find the path. The peculiarity of the behavior is that in the browser's url it is the only <a href> that adds the / to the url, even though in the html code it does not have the / in the href. I don't understand when the / is added, since all the pages are generated dynamically and go through the same process. This is the page sended to the browser with all links. The url is made dinamically with the slug of the model of each post. <h2><a href="/posts/first-post"> my post first </a></h2> <h2><a href="/posts/fourth-post"> my 4th post </a></h2> <h2><a href="/posts/ready-for-summer"> Ready for Summer Fun! </a></h2> <h2><a href="/posts/third-post"> my 3th post </a></h2> When you click to each links, everything goes fine and the page with the post is sended. the … -
add unit test in label-studio django project to azure storage
I am trying to add a new unit test to label-studio project I am not able to successfully create the storage upload below - name: stage request: data: container: pytest-azure-images project: '{project_pk}' title: Testing Azure SPI storage (bucket from conftest.py) use_blob_urls: true method: POST url: '{django_live_url}/api/storages/azure_spi' response: save: json: storage_pk: id status_code: 201 since I get last_sync_count: 0 in the results. How is the bucket from "conftest.py" being uploaded? - name: stage request: method: POST url: '{django_live_url}/api/storages/azure_spi/{storage_pk}/sync' response: json: last_sync_count: 0 status_code: 200 Here is my branch and PR if you can help: https://github.com/HumanSignal/label-studio/pull/5926/files -
Django allauth facebook login redirects to signup page
I have problem with logging to my app via Facebook. When I'm passing through facebook login form it redirect me to /accounts/social/signup/#= page in my app. My settings: ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" SOCIALACCOUNT_EMAIL_VERIFICATION = "none" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_CONFIRM_EMAIL_ON_GET = True SOCIALACCOUNT_AUTO_SIGNUP = True ACCOUNT_ADAPTER = "apps.users.adapter.MyAccountAdapter" SOCIALACCOUNT_ADAPTER = "apps.users.adapter.MySocialAccountAdapter" ACCOUNT_UNIQUE_EMAIL = False django-allauth version is 0.41.0 (it's old because it's legacy code) Interestingly, on test environment django-allauth does not redirect me (the same facebook client and secret and the same config) to signup page. What may cause the same configuration to work differently in different environments? I've tried with different config but still problem is the same. I don't want to be redirected to signup page. -
pyinstaller django :modules not found
i have turned my django application into exe file and i cant runserver , because some modules are not found django version 3.2.25 pyinstaller 5.12 at firrst runserver didnt work also so i used --noreload then it showed me another error about rest_framework C:\Users\GAMING\Documents\pythonexe1\project\dist>manage runserver --noreload Performing system checks... Traceback (most recent call last): File "rest_framework\settings.py", line 179, in import_from_string File "django\utils\module_loading.py", line 17, in import_string File "importlib\__init__.py", line 127, in import_module File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework.authentication' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 19, in <module> File "manage.py", line 16, in main File "django\core\management\__init__.py", line 419, in execute_from_command_line File "django\core\management\__init__.py", line 413, in execute File "django\core\management\base.py", line 354, in run_from_argv File "django\core\management\commands\runserver.py", line 61, in execute File "django\core\management\base.py", line 398, in execute File "django\core\management\commands\runserver.py", line 96, in handle File "django\core\management\commands\runserver.py", line 105, in run File "django\core\management\commands\runserver.py", line 118, in inner_run File "django\core\management\base.py", line 423, in check File "django\core\checks\registry.py", line 76, in run_checks File "django\core\checks\urls.py", line 13, in check_url_config File "django\core\checks\urls.py", line 23, in check_resolver File "django\urls\resolvers.py", line 416, … -
How can solve Target SWGI script '/aa/bb/wsgi.py' does not contain WSGI application 'application'?
When I change sqlite3 to postgresql, I receave error, this error I have only then I run apache2, if I start "manage.py runserver 0.0.0.0:8000" its work fine. I tried so many things, but I couldn't find the answer. psycopg2 is installed. Part of error: file "/../...postgresql/base.py", line 25.. import psycopg as Database ModuleNotFoundError: No module namged 'psycopg' file "/../...postgresql/base.py", line 27.. import psycopg2 as Database ModuleNotFoundError: No module namged 'psycopg2' .. .. Traceback (..): file /../../wsgi.py application =get_wsgi_application() .. .. .. .. mod_wsgi (pid-1111): Target SWGI script '/aa/bb/wsgi.py' does not contain WSGI application 'application' remove libraries and renew install, restart apache2, correct wsgi.py, 000-default.conf -
How to determine that the 'QuerySet' object does not have the 'comment' attribute in objects.filter(). Django
I am trying to display comments on the post page Comments Models.py from django.db import models from product.models import Product class Comment(models.Model): comment = models.TextField(name="comment") write = models.ForeignKey('product.Product', on_delete=models.CASCADE, null=True, blank=True, name="write") Product Models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=256, name="name") Product View.py def card(request, slug): product = Product.objects.get(id = slug) get_comments = Comment.objects.filter(write=product).distinct() print(get_comments.comment) context = {'product': product, 'comments': get_comments} return render(request, "product/card.html", context) In get_comments.comment I get the error 'QuerySet' object has no attribute 'comment' -
How to get the each unique data from one column
I have table like this below, ID value 1 test 2 test 3 trouble 4 trouble 5 test 6 ok 5 trouble This value column has three genres test trouble ok Now I want to get the unique array such as ['test','trouble','ok'] (any order is fine) How can I do this? -
Django Email Sending
I have a django project but when i try to use send_email() i get the following error: PS> daphne -p 8000 Server.asgi:application 2024-06-26 11:36:00,313 INFO Starting server at tcp:port=8000:interface=127.0.0.1 2024-06-26 11:36:00,313 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2024-06-26 11:36:00,313 INFO Configuring endpoint tcp:port=8000:interface=127.0.0.1 2024-06-26 11:36:00,314 INFO Listening on TCP address 127.0.0.1:8000 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Internal Server Error: /Http/createUser Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = await get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 253, in _get_response_async response = await wrapped_callback( ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 479, in __call__ ret: _R = await loop.run_in_executor( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ TimeoutError: [WinError 10060] The connected person does not respond within a certain period of time or the established connection could not be established because the connecting host was not responding 2024-06-26 11:37:01,353 ERROR Internal Server Error: /Http/createUser Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = await get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 253, in _get_response_async response = await wrapped_callback( ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line … -
How can I implement few checkboxes in a Django Form?
I was given a task to create a recipe website. A user can add a recipe. They have to choose a category (categories). One recipe can belong to one category or to several. I am inheriting my Form from ModelForm. Here's the code for it: class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['title', 'description', 'ingredients', 'cooking_steps', 'time', 'calories', 'portions', 'image', 'categories'] widgets = { 'title' : TextInput(attrs={'class' : 'create_recipe_title', 'placeholder' : 'Enter a title...' }), 'description' : TextInput(attrs={'class' : 'create_recipe_description', 'placeholder' : 'Enter a short description...' }), 'ingredients' : Textarea(attrs={'class' : 'create_recipe_ingredients', 'placeholder' : 'Your ingredients...', 'disabled' : True }), 'time' : NumberInput(attrs={'class' : 'create_recipe_time', 'placeholder' : 'Cooking time...' }), 'calories' : NumberInput(attrs={'class' : 'create_recipe_calories', 'placeholder' : 'Calories...' }), 'portions' : NumberInput(attrs={'class' : 'create_recipe_portions', 'placeholder' : 'Portions...' }), 'image' : FileInput(attrs={'class' : 'create_recipe_image'}), 'cooking_steps' : Textarea(attrs={'class' : 'create_recipe_cooking_steps', 'placeholder' : 'Describe the cooking process...' }), 'categories' : SelectMultiple(choices=[(1, 'Food'), (2, 'Drinks'), (3, 'Hot'), (4, 'Cold'), (5, 'Breakfast'), (6, 'Lunch'), (7, 'Dinner'), (8, 'Выпечка и десерты'), (9, 'Soups'), (10, 'Salads'), (11, 'Pizza and pasta'), (12, 'Sauces'),(13, 'Portugal'), (14, 'Italy'), (15, 'France'), (16, 'Japan'), (17, 'Chine'), (18, 'Georgia'), (19, 'Armenia'), (20, 'Mexico'), (21, 'Africa'), (22, 'Dietary'), (23, 'Sugar free'), (24, … -
Type Error while populating a model in Django with UniqueConstraint
I'm trying to build up my first project in Django and I'm having some issues while creating an entry into my model Prevision (including sales forecasts), which has a uniqueConstraint to ensure that there is only one forecast between a Supplier (model "Representada") and a Customer (model "Cliente") for a give year (field "Ano"). My models.py file is as follows: from django.db import models from django.db.models import CheckConstraint, Q, F, UniqueConstraint from django.db.models.signals import pre_save from django.dispatch import receiver from datetime import datetime # Create your models here. class Empresa (models.Model): CIF = models.CharField(max_length=9, unique=True, blank=True) Nombre = models.CharField(max_length=64) Telefono = models.CharField(max_length=16, blank=True) Email = models.EmailField(blank=True) Direccion = models.CharField(max_length=64) Ciudad = models.CharField(max_length=32) CP = models.PositiveIntegerField(default=1) Provincia = models.IntegerField(default=1) Contacto = models.CharField(max_length=64, blank=True) Observaciones = models.TextField(blank=True) def __str__(self): return f"{self.Nombre}" class Meta: abstract = True verbose_name_plural = "Empresas" constraints = [ ] class Representada (Empresa): Fecha_Alta = models.DateField() Fecha_Baja = models.DateField(blank=True, null=True) Porcentaje_Comision = models.DecimalField(max_digits=5, decimal_places=2) class Meta: verbose_name_plural = "Representadas" constraints = [ CheckConstraint( check = Q(Fecha_Baja__isnull=True)|Q(Fecha_Alta__lte=F('Fecha_Baja')), name = 'Comprobar fecha de alta y baja de representada', ), ] class Cliente (Empresa): Hay_Toro = models.BooleanField(blank=True) Inicio_Horario_Descarga = models.TimeField(blank=True, null=True) Fin_Horario_Descarga = models.TimeField(blank=True, null=True) def __str__(self): return f"{self.Nombre} ({self.Ciudad})" class Meta: … -
TimeoutError at /studentupdtpwd
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Request Method: POST Request URL: http://127.0.0.1:8000/studentupdtpwd Django Version: 5.0 Exception Type: TimeoutError settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@amil.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_TIMEOUT = 860 ``` While sending email from an Django application using send_mail or EmailMessage sometimes it is working fine but sometimes getting TIME OUT ERROR for same logic.I also created another app and updated settings.py new generated password. -
drf_yasg: Not able to generate Swagger UI from YAML file
I am using the drf_yasg library in my Django REST Framework project to generate Swagger documentation. I have defined my API endpoints and schemas in a YAML file, but when I try to generate the Swagger UI, it is not rendering correctly. It's rendering UI using auto-discovery, which does not have information about functions, but I want to add more information to it. Some key details: I have installed drf_yasg and added it to my Django INSTALLED_APPS I have defined my API endpoints and schemas in a swagger.yaml file In my Django URL config, I have added the get_schema_view() from drf_yasg to generate the schema This is my project urls.py from django.contrib import admin from django.urls import path, include from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework import permissions schema_view = get_schema_view( openapi.Info( title="My Application", default_version="v1", description="A sample API for learning DRF", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="hello@example.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('swagger/', schema_view.with_ui( 'swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui( 'redoc', cache_timeout=0), name='schema-redoc'), ] this how my function looks: @api_view(['POST']) def searchData(request): name = request.data.get('name') vendor = request.data.get('vendor') s = AppSearch() result = s.search(name, vendor) result = json.loads(json_util.dumps(result)) return Response(result, status=status.HTTP_200_OK) By default, Swagger is showing … -
How to code efficiently in a django project?
I am begineer in django, i am doing my first project in django. I am using mysql database with my project. Now while fetching data from the database and showing it in different sections of my projects need some logic, so i am using simple "for loops" , "if else statements" to do all this. I am also using boolean flags inside the database to execute different logic. I want to know, is this a correct approach to make a django project, or is there any startergy i should follow while adding new features or making new code ? Kindly help, I just want to know about the technique i should follow, as a begineer this question might be simple but it might be important for many as well. "A request, Please dont downvote this question for any unnecessary reason" -
How do I minify my HTML so that CSS and FontAwesome and Bootstrap names are reduced
I have a Django website that displays a table with data. It uses FontAwesome and Bootstrap for styling - which leads to some lengthy HTML (a standard page is 136k). Eg Some TDs contain an arrow using FA and a style to rotate it eg <i class="fa-solid fa-arrow-down fa-lg fa-rotate-by" style=--fa-rotate-angle:282deg></i> Is there a way to minify or some how reduce the name sizes? I have been reading about webpack and gulp minifiers but I cannot find anything that mentions the use of 3rd party assets like FA and BS and how one might reduce their name sizes. Also these seem somewhat targeted to client-side frameworks rather than server-side which mine is. -
ModuleNotFoundError: No module named 'rest_framework_simplejwt'
I am experiencing an issue with rest_framework_simplejwt when I try to run migrations in my Django project. The error I encounter is: ModuleNotFoundError: No module named 'rest_framework_simplejwt' I have verified that the library is installed: pip show djangorestframework-simplejwt Name: djangorestframework-simplejwt Version: 3.2.2 Summary: A minimal JSON Web Token authentication plugin for Django REST Framework Home-page: https://github.com/davesque/django-rest-framework-simplejwt Author-email: davesque@gmail.com License: MIT Location: \Programs\Python\Python311\Lib\site-packages Requires: django, djangorestframework, pyjwt Required-by: My INSTALLED_APPS includes the necessary applications: INSTALLED_APPS = [ 'app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist' ] Here are my REST_FRAMEWORK settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } And my SIMPLE_JWT settings: from datetime import timedelta SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "SIGNING_KEY": SECRET_KEY, "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "JTI_CLAIM": "jti", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } I don't understand where the problem comes from. I would appreciate any help to identify the issue. What I have tried: Installing different versions of … -
How to reduce the amount of HTML style code
I have a Django website that displays data in a table, most of the data is highlighted with a calculated background color to make it quickly obvious to the user. Is there a way to reduce the amount of HTML I am outputting? Eg: <td style=background-color:#5eff00>19</td> Ideally I'd use CSS - but I would literally be creating a class for every hex color value. Is there a better way? I did consider using the html bgcolor attribute but this is not supported by HTML5. Is this a possibility? -
Django code freezes using Daphne on async database queries
I am running an async django application that is downloading some data. As I want the downloads to run asynchronously, I defined some async methods to run as coroutines. These methods sometimes have Django ORM queries, which I also run asynchronously (async for loop, sync_to_async or .aget(), for example). Since I'd like to display the download progress in clients browser in realtime, I installed django-channels together with daphne to setup websockets. However, If I run my code without daphne, everything works perfect. But as soon as I register daphne as app in settings.py (that runserver is actually running daphne serevr), the code stucks at a async database query. More details: settings.py: ASGI_APPLICATION = 'MultiClaw.asgi.application' INSTALLED_APPS = [ 'daphne', ... ] The view, that is mapped to a button which starts the download: @csrf_exempt def start_grab_thread(request): parser_name = request.POST['parser_name'] settings_model = Settings.objects.filter(user=request.user, parser_name=parser_name)[0] parser_module = importlib.import_module(f'parser.Parser.{parser_name}') parser_class = getattr(parser_module, parser_name) parser_instance: Core = parser_class(settings_model) asyncio.run(parser_instance.download_products()) if request.method == "POST": return redirect('start') the function, where the problem occures: async def download_products(self): print('downloading products') collected_product_urls = self.product_url_list print(f'{collected_product_urls=}') product_urls_from_db = set([ product.source_url async for product in Product.objects .filter(pk__in=collected_product_urls) ]) print(f'{product_urls_from_db=}') print(f'FINALLY GOT IT') return I tried many attempts, wrap the query into a … -
infinte loop when transforming django into exe file
I want to execute " runserver" command and "run_file_watcher" which is custom command at the same time each one on a sperate thread , it works fine , but when transforming it into exe file with Pyinstaller it go for infinite loop this is the code for multithreading # run_both.py import os from threading import Thread import subprocess import sys import django # Set Django settings module explicitly os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() def run_django_server(): print("Starting Django server...") subprocess.run([sys.executable, 'manage.py', 'runserver']) print("Django server finished.") def run_custom_command(): print("Running custom command...") subprocess.run([sys.executable, 'manage.py', 'run_file_watcher']) print("Custom command finished.") if __name__ == "__main__": # Create threads thread1 = Thread(target=run_django_server) thread2 = Thread(target=run_custom_command) thread1.start() # returns immediately thread2.start() # returns immediately -
Django can`t find image
when i run my Djanfo app by daphne i get error WARNING Not Found: /media/images/lcg.jpg daphne -e ssl:8000:privateKey=ssl/privkey.pem:certKey=ssl/cert.pem website.asgi:application i set all setiings by guids and documantation settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('shop.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html {% for product in column1 %} <div class="item"> {% if product.img %} <img src="{{ MEDIA_URL }}{{ product.img }}" alt="{{ product.name }}" class="product-img"> {% endif %} tried add {% get_media_prefix as MEDIA_URL %} but nothing changed where product.img from DB - images\filename.png and i have this structure i had similar problen with static files but ChatGPT advised to use whitenoise and it solved problem but not with img