Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
With Django, is there a way to skip locked rows when performing an update?
I can do MyModel.objects.select_for_update(skip_locked=True) to grab rows that aren't locked. However, if I try to append an .update(some_field='whatever') to that, the UPDATE will sill apply to the FULL result set, including locked rows, and it will wait until the locked rows are freed up before executing (i.e. the select_for_update(skip_locked=True) portion is ignored in the update SQL that is sent). The SQL, in that scenario, will look like: UPDATE "my_model" SET "some_field" = 'whatever' I can get around this by first grabbing the IDs of the rows to update and then sending a separate query to update the rows: ids_to_update = list(MyModel.objects.select_for_update(skip_locked=True).values_list('id', flat=True) MyModel.objects.filter(id__in=ids_to_update).update(some_field='whatever') However, that requires 2 hits to the DB instead of 1 (I'm sure there's a way to do it with 1), and the rows that I'm updating, for the task at hand, have hundreds of thousands to millions of matches, so the 2-step approach is very memory-unfriendly and has high failure potential. Is there a non-raw-sql means of obtaining what I'm after with Django? If I have to resort to raw sql, what would that look like? -
How to send POST request with query params in django tests
I have test.py from rest_framework.test import APITestCase from django.core.files.uploadedfile import SimpleUploadedFile from django.urls import reverse class PostImageTest(APITestCase): def setUp(self) -> None: self.product = Product.objects.create(...) self.sampleImage = SimpleUploadedFile("test_image.jpg", b"binary data", content_type="image/jpeg") def test_with_valid_data(self) -> None: data = { "image":self.sampleImage, "is_featured":true } response = client.post(reverse('images'), data, format='multipart') I want to pass query params like images?product=id to the client.post() method. Also i'm not getting as to how to encode the image and send a POST request. When i tried like this response = client.post(reverse('images'), {'product' : self.product.id}, data=data, format='multipart') It gives me this error TypeError: Client.post() got multiple values for argument 'data' -
Chatgpt integration with Django for parallel connection
I'm using Django framework to have multiple chatgpt connection at same time but it's make complete code halt/down until chatgpt response is back. To encounter this i'm using async with Django channels but still its block Django server to serve any other resource. This is command to run Django server daphne --ping-interval 10 --ping-timeout 600 -b 0.0.0.0 -p 8000 backend.gradingly.asgi:application this is code which is calling chatgpt model = "gpt-4-0314" thread = threading.Thread(target=self.call_gpt_api, args=(prompt,model,context,)) thread.start() this is python code which is sending response to channels async_to_sync(channel_layer.group_send)( f'user_{context["current_user"]}',{ "type": "send_message", "text": json.dumps(json_data) } ) -
CSRF issue in the Django webpage deployed via Kubernetes pod
I am trying to deploy my web application that is written in Django, the image is build and already there, I am just deploying that image into a Kubernetes pod and running it. There is also an nginx pod that runs here. When I am trying to application via the pod and the port exposed through nginx, the error that I am getting is Forbidden (403) CSRF verification failed. Request aborted. I cannot change anything in the application directly. I am not posting the deployment file here as it is too big of a file, and there there is configmap and pv also involved in the backend. The application runs on http at the moment. The application takes me to the login page and after providing credentials it gives me this error. What are some of the things that I can try out. -
Too many redirects on nginx and django applicaiton.Redirecting all http request to https in django, nginx, uwsgi
I'm working on legacy code and trying to configure nginx and ssl certificate of the django based application as I'm not a system adminstrator but I'm trying. I have searched and tried almost all answers on stackoverflow and in the internet but I couldn't solve it. Here nginx configuration file is located on sites-enabled folder not sites-available. nginx version is 1.2.1 and django version is 1.11 # corpmanage.conf # the upstream component nginx needs to connect to upstream django { server unix:/home/corpmanage/corpmanage.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { listen 80; server_name mysite.com; server_name www.mysite.com; client_max_body_size 30m; # Django media location /media { alias /home/corpmanage/mediafiles; # your Django project's media files - amend as required } location /static { alias /home/corpmanage/static-prod; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed uwsgi_read_timeout 600; } } server { # the port your site will be served on listen 443 ssl; # the domain name it will serve for … -
can't redirect user to a certain page after login
so i'm working on a django project, i'm storing users info in phpmyadmin database, the signup process works well, but when a user tries to login , it just reloads the page, i tried to get the values of a record from the table if the username and password are correct (for example, username : ff, pass : ff1, if those are correct, it will display the values from the table, id : 2, email: dd@gg.com, username : ff, password : ff1) views.py : def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] # connect to MySQL database try: cnx = mysql.connector.connect(user='root', password='', database='projet') cursor = cnx.cursor() except mysql.connector.Error as error: print("Failed to connect to database: {}".format(error)) # retrieve user from database query = "SELECT * FROM projetpythonn_user WHERE username=%s AND password=%s" cursor.execute(query, (username, password)) user = cursor.fetchone() print(user) if user is not None: # create Django User object from database user user = authenticate(request, username=user[1], password=user[2]) if user is not None: # login user login(request, user) # redirect to YouTube return redirect('home') # if authentication fails, render login page with error message message = 'Invalid username or password' context = {'message': message} return render(request, 'login.html', context) … -
Range is not working when submit form (django)
we were working with Django and we have got a problem. Range doesn't working. Views.py: from django.shortcuts import render from shop_cookies_app.models import * # Create your views here. def show_catalog(request): response = render(request, "catalog.html", context={'products': Product.objects.all()}) if request.method == "POST": # product_count = request.POST.get("product_count") # product_count = int(product_count) # for i in range(product_count): if "product_pk" not in request.COOKIES: product = request.POST.get('product_pk') response.set_cookie('product_pk', product) return response else: product = request.COOKIES['product_pk'] + ' ' + request.POST.get('product_pk') response.set_cookie('product_pk', product) return response return response HTML: <h1>Каталог</h1> {% for product in products %} <h2>{{ product.name }}</h2> <p>{{ product.desc }}</p> <img src="{{ product.image.url }}" alt=""> <h3 class = "price"><span class = "spanPrice">{{ product.price }}</span> $</h3> <div class = "addAndRemove"> <div class = "buttons"> <button class = "plus">&plus;</button> <button class = "minus">&minus;</button> </div> </div> <form method = "POST" class = "addCookie"> <!-- action="{% url 'catalog' %}" --> {% csrf_token %} <input type="hidden" name="product_pk" value="{{ product.pk }}"> <input class = "count" name = "product_count" value = "1"> <button class = "addToCart">Додати до кошику</button> </form> {% endfor %} <script src = 'https://code.jquery.com/jquery-3.6.4.js' integrity="sha256-a9jBBRygX1Bh5lt8GZjXDzyOB+bWve9EiO7tROUtj/E=" crossorigin="anonymous" defer></script> <script src = '{% static "addCookie.js" %}' defer></script> JavaScript: $(document).ready(function () { // let madeBeforeFunctions = $(".count").val() function changeTimesPlus() { console.log("plus") let a = … -
Django rest framework CSRF_TRUSTED_ORIGINS settings not work
I am setting CSRF_TRUSTED_ORIGINS to make sure, when I send request from localhost it should not validate that. setting.py ... ... CSRF_TRUSTED_ORIGINS = [ ... 'http://localhost', 'https://localhost', 'http://127.0.0.1', 'https://127.0.0.1', ... ] ... ... When I send request it gives me error. curl -k --cert ~/.ssh/cert --key ~/.ssh/key https://localhost/api/v1/key/key/review/ -X PUT -H "Content-type: application/json" -H "Accept: application/json" -d '{"state": "APPROVED"}' --referer https://localhost {"detail":"CSRF Failed: Referer checking failed - https://localhost does not match any trusted origins."} I see localhost is in CSRF_TRUSTED_ORIGINS but still it complain about this. How can I set things where CSRF will be not checked for localhost? -
Structuring Docker Compose for larger Django backends
I'm currently trying to set up my backend with Docker Compose. I successfully managed to integrate my PostgreSQL database, my Django backend service as well as RabbitMQ message broker with each other. What I'm trying to achieve is setting up Celery workers, Celery beat and Celery Flower in separate Docker containers so my Django backend can work with them. The problem: My Celery tasks need to access Django's models and the database. Therefore, I need to copy some backend files into the Celery containers as well. I just don't feel like it's the best way to do that. I need to copy my entire backend, containing my tasks, routines, models, urls and views to get my Celery workers to actually run. What would be the best workflow to realize that? -
Using dj_rest_auth with Django and Azure
I am trying to enable signing in with Azure for a Django app My URL folder is as follows: path("dj-rest-auth/", include("dj_rest_auth.urls")), path("dj-rest-auth/azure/", azure_login.as_view(), name="azure_login"), views.py as follows from allauth.socialaccount.providers.azure.views import AzureOAuth2Adapter from dj_rest_auth.registration.views import SocialLoginView class azure_login(SocialLoginView): adapter_class = AzureOAuth2Adapter client_class = OAuth2Client callback_url = "http://localhost:8000/accounts/azure/login/callback/" I am getting the following error and I understand that I should not pass an Access Token OAuth2Error at /dj-rest-auth/azure/ Error retrieving access token: b'{"error":"invalid_request","error_description":"AADSTS9002339: Unsupported user account for this endpoint. The user is a Microsoft Accounts user, but this app does not have the Microsoft account audience enabled. Either enable Microsoft account support to use the /common endpoint or use the tenanted endpoint to target a specific Azure AD tenant for auth I think this "use the tenanted endpoint to target a specific Azure AD tenant for auth" , we should be able to specify the tenant info somewhere. -
SocialAuth integration using Django and React with Azure
My URL folder is as follows: path("dj-rest-auth/", include("dj_rest_auth.urls")), path("dj-rest-auth/azure/", azure_login.as_view(), name="azure_login"), views.py as follows from allauth.socialaccount.providers.azure.views import AzureOAuth2Adapter from dj_rest_auth.registration.views import SocialLoginView class azure_login(SocialLoginView): adapter_class = AzureOAuth2Adapter When I navigate to http://127.0.0.1:8000/dj-rest-auth/azure/, How can I pass these values from the frontend react code? const handleAzureLogin = async (e) => { try { e.preventDefault(); const codeParams = { "code": "AAAAA" }; What should I do here? const { data } = await axios.post(`${API_BASE_URL}/dj-rest-auth/azure/`, codeParams); console.log(data) window.location.href = data.url; } catch (err) { console.log('Error:', err); console.log('Error response data:', err.response.data); } }; -
Websocket connection through nginx returns 400 - Hixie76 protocol not supported
I have a (fairly complex) django app hosted on AWS via Elastic Beanstalk, and am trying to implement websockets on it, using django-channels Here is the docker-compose.yml file sent to elastic beanstalk: version: "3.8" services: migration: build: . env_file: - .env command: python manage.py migrate api: build: . env_file: - .env command: daphne myapp.asgi:application --port 8000 --bind 0.0.0.0 deploy: restart_policy: condition: on-failure delay: 5s max_attempts: 3 window: 120s expose: - 8000 depends_on: - migration nginx: image: nginx:1.21.0-alpine env_file: - .env volumes: - ./nginx/templates:/etc/nginx/templates - ./nginx/certs:/etc/nginx/certs ports: - 80:80 - 443:443 depends_on: - api deploy: restart_policy: condition: on-failure delay: 5s max_attempts: 3 window: 120s Here is the nginx config file: server { listen 80; listen [::]:80; location /health/ { proxy_pass http://api:8000/health/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; listen [::]:443 ssl; root /usr/share/nginx/html/; index index.html; ssl_certificate /etc/nginx/certs/public.crt; ssl_certificate_key /etc/nginx/certs/myapp.pem; location / { proxy_pass http://api:8000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_read_timeout 300s; } client_max_body_size 5M; } When running on my local machine, everything runs smooth. … -
Django - Return remaining throttle calls available
I am trying to retrieve the remaining calls available with no luck, the use case is sending that data in the response or headers to the frontend, so that the end user can check the credit of API calls available settings.py REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.ScopedRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'my_view': '10/day', } } views.py class MyView(APIView): throttle_classes = [ScopedRateThrottle] throttle_scope = 'my_view' -
Somebody help please [closed]
Command Prompt-python manage.py runnerver C:\Users\jeanl\lecture3>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Jeanl\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\uris\resolvers.py", line 717, in url patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\jeanl\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1838, in bootstrap_inner self.run() File "C:\Users\jeanl\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self. target("self._args, **self. wargs) File "C:\Users\jean1\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, *args) File "C:\Users\jean1\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner run self.check(display_num_errors=True) File "C: Misers\jean1 VApplata\Local\Programs\Python\Python311\Lib\site-packages\django\core\nanagement\base.py all issues checks.run checks( ", line 485, in check File "C:\Users\JeanlopData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run checks new_errors= check(app_configs-app_configs, databases-databases) File "C:\Users\Jean1VppData\Local\Programs\Python\Python311\lib\site-packages\django\core\checks \urls.py", line 42, in check_url_namespaces_unique all namespaces load all nanespaces(resolver) File "C:\Users\Jean1VppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces (pattern, current)) File "C:\Users\Jeanl\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 61, in load_all_namespaces url patterns getattr(resolver, "url patterns", []) File "C:\Users\Jean1\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 57, in get_ res instance._dict [self.nase] self.func(Instance) File "C:\Users\Jean]\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\resolvers.py", line 725, in url patterns raise ImproperlyConfigured (msg.format(name-self.urlconf_name)) from e django.core.exceptions. ImproperlyConfigured: The included URL cont module "hello.urls' from 'C:\Users\Jean]\lecture3\hello\urls.py's does not appear to have any patterns in it. If you see the 'urlpatterns variable with valid patterns in the file then the issue … -
Django allauth - SocialTokens table empty after Google Login
Python: 3.8.10 Django: 4.1.7 django-allauth: 0.54.0 I'm working on a webpage which I have to connect to the Company Google Workspace. I correctly managed the login, with no issues. Now, I have to connect to the Gmail of the authenticated user. For connecting to Google Apps I need a Token that, as I understood, should be in the Database in the table SocialTokens (automatically filled-in after the login phase). I populated Sites and Social Application manually, and rightly (I guess) based on fact that login works. The authentication works properly, but after the login the model SocialToken (table "Social application tokens") is still empty. But I cannot figure out why the table SocialTokens is not populated after the correct Google login. Here my settings.py SITE_ID = 1 INSTALLED_APPS = [ 'django.contrib.admin', ..., 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] SOCIALACCOUNT_PROVIDERS = { 'google':{ 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': {'access_type':'offline'}, } } SOCIALACCOUNT_STORE_TOKEN = True SOCIALACCOUNT_AUTO_SIGNUP = True I tried what below: update django-allauth (0.4 --> 0.54) SOCIALACCOUNT_STORE_TOKEN = True --> set False, True and unset(commented and deleted) SOCIALACCOUNT_AUTO_SIGNUP = True --> set False, True and unset(commented and deleted) two lines above in all their combinations (es. SOCIALACCOUNT_STORE_TOKEN = True and SOCIALACCOUNT_AUTO_SIGNUP … -
Crontab inside a Bash file
I want to start my django project and execute every 10 min a BaseCommand. I wrote bash file it doesn't seem to work. I have some cronjob code but I don't know if this is enough... */10 * * * * python3 manage.py read_create_earning_reports ...or activating the virtual environment for the crontab is neccessary. */10 * * * * cd /Users/andreysaykin/Documents/project_distrokid/project_dk && source ../bin/activate && python3 manage.py myBaseCommand Afterwards I start my server. cd /my/django/project/path source ../bin/activate python3 manage.py runserver What my current Problem is that I am getting this Error: /Users/username/Documents/bash/myScript.sh: line 2: */10: No such file or directory -
Fail dockerizing Django+ PostgreSQL project due to problem with installing psycopg2
I created a Django project which uses PostgreSQL as database. I already have PostgreSQL container and was trying to create an image of my project when I faced the following errors: Preparing metadata (setup.py): started #8 46.75 Preparing metadata (setup.py): finished with status 'error' #8 46.75 error: subprocess-exited-with-error #8 46.75 #8 46.75 × python setup.py egg_info did not run successfully. #8 46.75 │ exit code: 1 #8 46.75 ╰─> [25 lines of output] #8 46.75 /usr/local/lib/python3.12/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. #8 46.75 warnings.warn(msg, warning_class) #8 46.75 running egg_info #8 46.75 creating /tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info #8 46.75 writing /tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info/PKG-INFO #8 46.75 writing dependency_links to /tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info/dependency_links.txt #8 46.75 writing top-level names to /tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info/top_level.txt #8 46.75 writing manifest file '/tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info/SOURCES.txt' #8 46.75 #8 46.75 Error: pg_config executable not found. #8 46.75 #8 46.75 pg_config is required to build psycopg2 from source. Please add the directory #8 46.75 containing pg_config to the $PATH or specify the full executable path with the #8 46.75 option: #8 46.75 #8 46.75 python setup.py build_ext --pg-config /path/to/pg_config build ... #8 46.75 #8 46.75 or with the pg_config option in 'setup.cfg'. #8 46.75 #8 46.75 If you prefer to avoid building psycopg2 from source, please install … -
Django admin autocomplete_fields saving everything in queryset
I am using Django Admin autocomplete_fields to save a bunch of zipcodes. I want to be able to save all the zipcodes in the queryset. Is that possible? I tried overwriting a bunch of methods but nothing has helped so far. -
Django mail error SMTPServerDisconnected: Connection unexpectedly closed even after setting all the correct details (including DEFAULT_FROM_EMAIL)
I am facing various problems (errors) while trying to send mail through django. I have checked other stackoverflow questions but none helped me Django version - 4.2 Django email specific settings- EMAIL_HOST = "county.herosite.pro" EMAIL_PORT = 465 # EMAIL_USE_SSL = True EMAIL_USE_TLS = True EMAIL_HOST_USER = "noreply@bulltrek.com" DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASWORD = "myPassword" Commands ran in django shell In [1]: from django.core.mail import send_mail In [2]: sender_email = "noreply@bulltrek.com" In [3]: send_mail("Hola","Gola",sender_email,[sender_email]) Error I got --------------------------------------------------------------------------- SMTPServerDisconnected Traceback (most recent call last) Cell In[4], line 1 ----> 1 send_mail("Hola","Gola",sender_email,[sender_email]) File ~/snadeepAlgoTradingPlatform/env/lib/python3.11/site-packages/django/core/mail/__init__.py:87, in send_mail(subject, message, from_email, recipient_list, fail_silently, auth_user, auth_password, connection, html_message) 84 if html_message: 85 mail.attach_alternative(html_message, "text/html") ---> 87 return mail.send() File ~/snadeepAlgoTradingPlatform/env/lib/python3.11/site-packages/django/core/mail/message.py:298, in EmailMessage.send(self, fail_silently) 294 if not self.recipients(): 295 # Don't bother creating the network connection if there's nobody to 296 # send to. 297 return 0 --> 298 return self.get_connection(fail_silently).send_messages([self]) File ~/snadeepAlgoTradingPlatform/env/lib/python3.11/site-packages/django/core/mail/backends/smtp.py:127, in EmailBackend.send_messages(self, email_messages) 125 return 0 126 with self._lock: --> 127 new_conn_created = self.open() 128 if not self.connection or new_conn_created is None: 129 # We failed silently on open(). 130 # Trying to send would be pointless. 131 return 0 File ~/snadeepAlgoTradingPlatform/env/lib/python3.11/site-packages/django/core/mail/backends/smtp.py:85, in EmailBackend.open(self) 83 connection_params["context"] = self.ssl_context 84 try: ---> 85 self.connection = self.connection_class( … -
Unable to run the command "python manage.py migrate"
I am trying to setup a virtual environment to test a website I'm working on that is running on django. When I created the project, it didn't include a settings.py file which I got a lot of errors about before and added one using a base example and changed some things. I then added django.contrib.sites to my settings.py file which others said helped, but didn't fix it. I ran the following commands pip install -r req.txt and when I try to run python manage.py migrate I get the error >> Traceback (most recent call last): File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\manage.py", line 22, in <module> main() File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\migrate.py", line 100, in handle self.check(databases=[database]) File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File … -
Image upload for image processing to fill up related form fields in Django
I am new to Django. My task is to upload an image and do some image processing on it and fill up some fields based on the results obtained from the image. Then the user would maybe check if the values that get filled in are correct and if they are they will save the whole form with the image and all the other form fields. So, I am confused about the following. I already have the util functions for the image processing which is in python. How should I obtain the image immediately after the user select the file and do the image processing and receive my data from the processing keeping in mind that this will be happening in the server. My url for this page is "admin/book/add". I am not providing any code because I wanted to the general way of how to do something like this in django. My model includes -> BookModel: name, author, year ImageModel: Image, Image_thumbnail. // this will be filled after image processing Constructs: x, y, z Finally, the user will hit the save button and save I have tried using javascript to send AJAX and send the image only to backend, … -
How do I use a dict to translate ArrayAgg values for an annotation in Django?
I'm using Django 4 with Postgres. Say I have two related models like this: class Company(Model): ... class Address(Model): city = CharField(...) companies = ManyToManyField( Company, through=ThroughCompanyAddress, related_name="addresses" ) ... class ThroughCompanyAddress(Model): company_id = ForeignKey(Company, ...) address_id = ForeignKey(Address, ...) I want to annotate the cities that each company is in. Normally, I would do something like this: Company.objects.all().annotate(cities=ArrayAgg("addresses__city")) Unfortunately, because of the way my DevOps team has the databases configured, these tables are stored on different databases, and I can't do this. Instead, I need to do 2 queries - first, to get a mapping of address ids to city names, and then to somehow use that mapping to annotate them onto the company models. # After the initial query to the first database, I end up with this # Note: The int dict keys are the address model Primary Keys cities = {1: "Paris", 2: "Dubai", 3: "Honk Kong"} # Now how do I use this dict here? Company.objects.all().annotate( city_ids=Subquery( # Not tested, but I think something like this would work ThroughCompanyAddress.objects.filter( company_id=OuterRef('id') ).values("address_id") ) ).annotate(cities=???) How do I use the cities dict in my annotation here to translate city_ids to city names? I probably could do a … -
What does it mean Redis URL must specify one of the following schemes (redis://, rediss://, unix://)
I am getting this error message after a file upload is completed and the redirect is meant to take place. Redis URL must specify one of the following schemes (redis://, rediss://, unix://) I am not sure what the problem is as i am extremely new to django channels and redis, never used it before so i dont even understand this error. Basically i have everything from consumers.py,routing.py and a view function to handle file upload. -
Log results of asynchronous processes to a database field
I am working on a project using Django and Celery which takes large files and processes them in multiple steps. The main object for the file is called Sequencing and only one is created per file. Now for every Sequencing we create many samples, variations etc. Some of these are already in the db so we use a get or create. After the processing of each Sequencing, I would like to have the amount of created and the amount of reused objects written into a json field called metadata in the Sequencing object but as some processes run asynchronously, this does not work out. Some code excerpts: models.py: class Sequencing(...): metadata = models.JSONField( default=dict, blank=True, ) def log(self, level: str, msg: str | list, *args, **kwargs) -> None: """Records messages for users in metadata.""" if "log" not in self.metadata: self.metadata["log"] = [] self.metadata["log"].append( { "date": datetime.datetime.utcnow().isoformat(), "level": level, "msg": msg, } ) self.save() def load(self) -> None: chain( ... sequencing_load_variants.si(self.id), ... ) def load_variants(self) -> None: ... for contig in contigs: sequencing_load_variants_by_contig.delay(self.pk, contig=contig) def load_variants_by_contig(self, contig: str) -> None: # create samples # create variants .... self.log( "info", [f"Variants created for region {region.seqid}: {log_dict['variants_create']}"] + [f"Variants found for region {region.seqid}: … -
Form set admin django
I am a beginner programmer Qiez project There is a task in admin On one page Ability to add questions/answers to questions/mark correct answers on the test set page Tried NestedStackedInline, NestedModelAdmin Lots of settings Is there a better option