Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery can't launch tasks by schedule despite settings
I have a django project with this code: settings.py CELERY_ENABLE_UTC = False CELERY_TIMEZONE = 'Asia/Omsk' celery.py # -*- coding: utf-8 -*- from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sendings.settings') app = Celery('sendings') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'sending_to_emails': { 'task': 'app.tasks.sendings', 'schedule': crontab(minute=36, hour=22) }, } In my docker-container based on alpine image i check datetime and it's correct accordings with my tz settings. I down my docker containers and rebuild them, but this problem still remains. -
Creating Order instance in django/ choose the existing customer or add new customer
I am building an inventory management system. In this template I allowing to either choose an existing customer or add new. However, even though i am able to save orders when creating a new customer instance, i am not able to do so with the existing customer. I used some javascript to disable the fields accordingly, however it is still not working create_order.html {% extends "inventory/layout.html" %} {% block body %} <h1>Create Order</h1> <form method="POST" action="{% url 'create_order' %}"> {% csrf_token %} <!-- Customer form section --> <h4>Customer Information</h4> <div class="form-group"> <input type="radio" id="existing_customer_radio" name="customer_option" value="existing" checked> <label for="existing_customer_radio">Select Existing Customer:</label> <select id="existing_customer" name="existing_customer"> <option value="">---------</option> {% for customer in existing_customers %} <option value="{{ customer.id }}">{{ customer.name }}</option> {% endfor %} </select> </div> <div class="form-group"> <input type="radio" id="new_customer_radio" name="customer_option" value="new"> <label for="new_customer_radio">Create New Customer:</label> <div id="new_customer_form" style="display: none;"> {{ customer_form.as_p }} </div> </div> <!-- Order form section --> <h4>Order Items</h4> {{ formset.management_form }} {% for form in formset.forms %} <div class="order-item-form"> {{ form.as_table }} </div> {% endfor %} {{ order_form.as_p }} <button type="submit">Save Order</button> </form> <script> // Show/hide new customer form based on selected radio button var existingCustomerRadio = document.getElementById("existing_customer_radio"); var newCustomerRadio = document.getElementById("new_customer_radio"); var newCustomerForm = document.getElementById("new_customer_form"); var customerFormFields … -
Allauth with JWT
My project requires JWT authentication, but also allauth is needed. How can i get JWT tokens after login via socials? I have surfed the net completely and tired of seeking the answer, the last hope I have is here, i guess... I tried using simple_jwt but didn`t get any result. Also used dj-rest-auth but it is complicated. I guess the clue in dj-rest-auth, but i cannot find out how to use it. I got an answer from net with this example: class GitHubLogin(SocialLoginView): adapter_class = GitHubOAuth2Adapter callback_url = "http://localhost:8000/" client_class = OAuth2Client but it requires those 3 credentials: access_token, code and id_token. Surfing the net i haven`t found any proper answer( -
strang result from django annotate or django dublicate the resulte
I have this code centers = Center.objects.filter(branch=request.user.center.branch,name="test").annotate( transaction_out=Coalesce(Sum('_TransactionOut__amount', filter=Q(_TransactionOut__date_time__gte=thirty_days_ago)),Value(0.0)), ) the result of transactio_out is 2000 which is correct but if i add a new field to annotate called transaction in transaction_in=Coalesce(Sum('_TransactionIn__amount', filter=Q(_TransactionIn__date_time__gte=thirty_days_ago)),Value(0.0)), it dublicate the reselut for example 2000 --> 4000 5000 --> 10,000 full code : centers = Center.objects.filter(branch=request.user.center.branch,name="test").annotate( transaction_in=Coalesce(Sum('_TransactionIn__amount', filter=Q(_TransactionIn__date_time__gte=thirty_days_ago)),Value(0.0)), transaction_out=Coalesce(Sum('_TransactionOut__amount', filter=Q(_TransactionOut__date_time__gte=thirty_days_ago)),Value(0.0)), ) class TransactionIn(models.Model): amount = models.FloatField() center=models.ForeignKey("center.Center",on_delete=models.SET_NULL,null=True,blank=True, related_name="_TransactionIn") class TransactionOut(models.Model): amount = models.FloatField() user=models.ForeignKey("account.User",on_delete=models.SET_NULL,null=True,blank=True)# related name center=models.ForeignKey("center.Center",on_delete=models.SET_NULL,null=True,blank=True, related_name="_TransactionOut") class Center(models.Model): name = models.CharField(max_length=35) database query : SELECT "center_center"."id", "center_center"."name", "center_center"."branch_id", "center_center"."image", "center_center"."manager_id", "center_center"."lat", "center_center"."long", "center_center"."mobile_number", COALESCE(SUM("accounting_transactionin"."amount") FILTER (WHERE "accounting_transactionin"."date_time" >= '2023-06-10T21:08:09.278740+00:00'::timestamptz), 0.0) AS "transaction_in", COALESCE(SUM("accounting_transactionout"."amount") FILTER (WHERE "accounting_transactionout"."date_time" >= '2023-06-10T21:08:09.278740+00:00'::timestamptz), 0.0) AS "transaction_out" FROM "center_center" LEFT OUTER JOIN "accounting_transactionin" ON ("center_center"."id" = "accounting_transactionin"."center_id") LEFT OUTER JOIN "accounting_transactionout" ON ("center_center"."id" = "accounting_transactionout"."center_id") WHERE ("center_center"."branch_id" = 1 AND "center_center"."name" = 'test') GROUP BY "center_center"."id" -
How to fix: "TypeError: 'Meta.fields' must not contain non-model field names: order_by"
I'm updating the Django version in a project, I've never done that before and I'm facing a lot of problems, one of them is this one, and so far I couldn't find the solution. Full error description: **File "/venv/lib/python3.10/site-packages/django_filters/filterset.py", line 358, in get_filters raise TypeError(TypeError: 'Meta.fields' must not contain non-model field names: order_by) ** Here are the requirements I'm currently using: arabic-reshaper==3.0.0 asgiref==3.7.2 astroid==2.4.2 autopep8==1.5.4 boto3==1.13.3 botocore==1.16.3 certifi==2020.4.5.1 chardet==3.0.4 colorama==0.4.3 cssselect2==0.7.0 dj-database-url==0.5.0 Django==4.1 django-rest-auth==0.9.5 django-allauth==0.53.0 django-translation==1.2 django-after-response==0.2.2 django-cors-headers==3.2.1 django-crispy-forms==1.9.1 django-ebhealthcheck==1.0.1 django-extensions==2.2.9 django-filter==2.4.0 django-sass==1.0.0 django-seed==0.2.2 django-storages==1.9.1 djangorestframework==3.14.0 djangorestframework-filters==1.0.0.dev2 djangorestframework-simplejwt==4.5.0 docutils==0.15.2 Faker==4.0.3 gunicorn==20.0.4 html5lib==1.1 idna==2.9 isort==5.4.2 jmespath==0.9.5 lazy-object-proxy==1.4.3 libsass==0.20.0 lxml==4.9.2 mccabe==0.6.1 numpy==1.24.2 pandas==1.3.5 Pillow==9.4.0 psycopg2==2.8.4 pycodestyle==2.6.0 pydot==1.4.1 PyJWT==1.7.1 pylint==2.6.0 pyparsing==2.4.7 PyPDF2==1.26.0 PyPDF3==1.0.6 python-bidi==0.4.2 python-dateutil==2.8.2 pytz==2022.7.1 reportlab==3.6.12 requests==2.23.0 s3transfer==0.3.3 selenium==3.141.0 sentry-sdk==0.14.4 six==1.16.0 sqlparse==0.3.1 svglib==1.5.1 text-unidecode==1.3 tinycss2==1.2.1 toml==0.10.1 tqdm==4.65.0 urllib3==1.25.9 webencodings==0.5.1 whitenoise==5.0.1 wrapt==1.12.1 xhtml2pdf==0.2.6 xlrd==1.2.0 here are the old requirements: arabic-reshaper==3.0.0 asgiref==3.2.7 astroid==2.4.2 autopep8==1.5.4 boto3==1.13.3 botocore==1.16.3 certifi==2020.4.5.1 chardet==3.0.4 colorama==0.4.3 cssselect2==0.7.0 dj-database-url==0.5.0 Django==3.0.5 django-after-response==0.2.2 django-cors-headers==3.2.1 django-crispy-forms==1.9.1 django-ebhealthcheck==1.0.1 django-extensions==2.2.9 django-filter==2.2.0 django-sass==1.0.0 django-seed==0.2.2 django-storages==1.9.1 djangorestframework==3.11.0 djangorestframework-filters==1.0.0.dev0 djangorestframework-simplejwt==4.5.0 docutils==0.15.2 Faker==4.0.3 gunicorn==20.0.4 html5lib==1.1 idna==2.9 isort==5.4.2 jmespath==0.9.5 lazy-object-proxy==1.4.3 libsass==0.20.0 lxml==4.9.2 mccabe==0.6.1 numpy==1.24.2 pandas==1.3.5 Pillow==9.4.0 psycopg2==2.8.4 pycodestyle==2.6.0 pydot==1.4.1 PyJWT==1.7.1 pylint==2.6.0 pyparsing==2.4.7 PyPDF2==1.26.0 PyPDF3==1.0.6 python-bidi==0.4.2 python-dateutil==2.8.2 pytz==2022.7.1 reportlab==3.6.12 requests==2.23.0 s3transfer==0.3.3 selenium==3.141.0 sentry-sdk==0.14.4 six==1.16.0 sqlparse==0.3.1 svglib==1.5.1 text-unidecode==1.3 tinycss2==1.2.1 toml==0.10.1 tqdm==4.65.0 urllib3==1.25.9 webencodings==0.5.1 whitenoise==5.0.1 … -
Unable to consistenly show embed pdf on browser
I'm using Django to send a PDF to my frontend, where the file is displayed embedded in the HTML. The problem I'm facing is that the PDF viewer is showing the correct number of pages for the file, but all the pages are blank. For some files, the content is displayed correctly, but for others, only blank pages are visible. This is the code I'm using on my backend: import base64 with open(new_path, 'rb') as file: archivo_pdf = file.read() archivo_pdf = base64.b64encode(archivo_pdf).decode('utf-8') respuesta_json = { 'archivo_pdf': archivo_pdf, 'fecha': new_fecha } return JsonResponse(respuesta_json) And this is the code I'm using on the frontend to process the file: var contenidoPDF = atob(response.archivo_pdf) var blob = new Blob([contenidoPDF], { type: 'application/pdf' }); var url = URL.createObjectURL(blob); $('#pdf-container').html('<object data="' + url + '" type="application/pdf" width="1100" height="800"><embed src="' + url + '" type="application/pdf"></object>'); I tried using PyPDF2 to return the file since I read that it might help, but it didn't work. I also tried changing the "decode" method used, but it still doesn't work. Can someone give me some guidance on what I might be doing wrong? -
How to add active class in django?
I have a sidebar where there are links to some pages that have active class if url matches to name of link. But there are also links to pages that I add with for loop in my template. I need to somehow add active class when they are opened. I use id to link them. template: {% for branch in branches %} <li> <a href="{% url 'manager-branch-workers' branch.id %}">{{branch.name}}</a> </li> {% endfor %} urls.py: urlpatterns = [ ... path('workers/<int:pk>/', views.BranchWorkerList, name='manager-branch-workers') ] Can I check id and url path? -
Request.user gives anonymous user in JWT
In my django rest framework project I used json web tocken based authentication I want to access requested user object to pass as foreign key when I try request.user it will return AnonymousaUser The authentication is passed How can I get request.user at views in JWT drf and react project -
django - annotate a field and return the queryset including that field?
I have been at this for 3 hours. last_prices = ( UsStockPriceModel.objects .filter(ticker__in=tickers) .order_by('ticker', '-last_date_time') .distinct('ticker') .values('ticker', 'last_price') ) last_close_dict = {price['ticker']: price['last_price'] for price in last_prices} # tried, error annotate got a non-expression dca_orders = self.request.user.dca_orders.all().annotate( last_close_price=DecimalField(default=0.0) ) # tried, standalone and with above statement for instruction in dca_orders: instruction.last_close_price = last_close_dict.get(instruction.ticker, 0.0) I have tried using Case and a lot of other things. For some reason the last_close_price field is never returned. It is not a part of the model, I need the field only in specific cases. -
Django Can't Find a static file that's already there
I'm facing a very peculiar problem using Django. So basically I have a CSS static file inside <static/css> directory, and here's the strange message from terminal: "GET /home/.../django/mysite/static/css/style.css HTTP/1.1" 404 1932, while the file is actually there! settings file: DEBUG = True ALLOWED_HOSTS = ['*'] STATIC_URL = str(BASE_DIR) + '/static/' STATIC_ROOT = str(BASE_DIR.joinpath('static')) STATICFILES_DIR = (str(BASE_DIR.joinpath('static')),) I have used the command "python manage.py collectstatic", but it didn't work; I also checked out this page: https://docs.djangoproject.com/en/4.2/howto/static-files/ but there was no solution for me... Please tell me what's wrong! -
how to get response headers in django , when using rest framework response
I am trying to get response headers as i see in postman . I am using response.headers which works fine on my local server , but when hosted it gives error . So I tried using response.items() to find the response headers , which works well . But I am looking over the headers i get on postman like enter image description here Please let me know if there is any lead in this regard -
Django: cached_db SESSION_ENGINE causes "SessionInterrupted" exception
Configuration: django 3.2 using cached sessions in REDIS Moved from SESSION_ENGINE 'django.contrib.sessions.backends.cache' to 'django.contrib.sessions.backends.cached_db' as suggested in the django documentation "This avoids edge cases caused by unreliable data storage in production." Now following issues arises from time to time: When storing some data in the session, django crashes with error "SessionInterrupted The request's session was deleted before the request completed" Debugging this reveals the following: Since the session has been updated, django tries to save it in the db. But the session there does not exist. Since the session save is done with parameter "force_update" (in django.contrib.sessions.backends.db.py called from django.contrib.sessions.backends.cached_db.py), the update fails and raises an exception leading to this error message. Session settings: SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 1209600 # 2 weeks in seconds SESSION_REMEMBER = True SESSION_COOKIE_SAMESITE = None Questions: So how to solve this? How can the session disappear from the db? (timeout?) Why does the save routine use "force_update=True" (removing this parameter effectively solves the issue in this case) -
Does anyone know what cause this following error: (I use vercel to deploy my django code online)
error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully.│ exit code: 1╰─> [35 lines of output]/tmp/pip-build-env-l6u27ub6/overlay/lib/python3.9/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in setup.cfg!! \\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\* The license_file parameter is deprecated, use license_files instead. By 2023-Oct-30, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. \\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\*\\\* !!parsed = self.parsers.get(option_name, lambda x: x)(value)running egg_infowriting psycopg2.egg-info/PKG-INFOwriting dependency_links to psycopg2.egg-info/dependency_links.txtwriting top-level names to psycopg2.egg-info/top_level.txt Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directorycontaining pg_config to the $PATH or specify the full executable path with theoption: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at<https://www.psycopg.org/docs/install.html\>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip.error: subprocess-exited-with-error note: This error originates from a subprocess, and is likely not a problem with pip.Traceback (most recent call last):File "/vercel/path0/manage.py", line 11, in mainfrom django.core.management import execute_from_command_lineModuleNotFoundError: No module named 'django'The above exception was the direct cause of the following … -
'Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)
Im using a 3rd party api service for a text sending job. When I send around 5000 numbers as payload to the API, it works fine. I have noticed that sometimes when the payload count exceeds to 7000 or above. I receive the following error code in response from the api. 'Connection aborted.', RemoteDisconnected('Remote end closed connection without response',) msg_dict['test'] = test msg_dict_json = json.dumps(msg_dict) data = { 'apikey': apikey, 'data': msg_dict_json, } res = requests.post('https://api.txtlocal.com/bulk_json/', data=data) return res sample data obj: data={ "api_key": api_key, "data": '{"sender": "abc", "messages": [{"number": "+0000000000", "text": "some text"}], "test": true}' } data['data'] can be over 7000 objects (which is causing the issue) I know there's a limit of 10000 users per api call for this api: https://api.txtlocal.com/bulk_json/ so my payload count always stays less than 10000. PS: The request doesnt rollback, sms are sent to the user even when I get a response as mentioned above. Just I dont receive a positive response and it throws exception. Also i want to mention that I have successfully been able to send 7 to 8000 sms with successful response but now its sending this issue. Any help would be appreciated, thanks. -
(Linux-Ubunto Permission problem) Nginx can't load static/media files from Django Site
this is more of linux permission problem. Im trying to create a website with nginx and django, but I'm getting error 403 forbidden, so my nginx is not able to read my statics files, I'm not experienced with linux(Ubunto) failed to load resource: the server responded with a status of 403 (Forbidden) I will show you my file permissions: ls -ld /home/jamelaumn/myproject drwxr-xr-x 11 www-data www-data 4096 Jul 9 23:25 /home/jamelaumn/myproject ls -ld /home/jamelaumn/myproject/deploystatic drwxr-xr-x 6 www-data www-data 4096 Jul 9 23:22 /home/jamelaumn/myproject/deploystatic ls -ld /home/jamelaumn/myproject/media drwxr-xr-x 4 www-data www-data 4096 Jul 9 23:25 /home/jamelaumn/myproject/media ls -ld /home/jamelaumn/myproject/media/product_images drwxr-xr-x 4 www-data www-data 4096 Jul 9 23:25 /home/jamelaumn/myproject/media/product_images ps aux | grep nginx root 281102 0.0 0.5 195928 6280 ? Ss 14:52 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; www-data 281103 0.0 1.2 196552 13340 ? S 14:52 0:00 nginx: worker process root 281116 0.0 0.1 3452 1576 pts/0 S+ 15:00 0:00 grep --color=auto nginx ps aux | grep /home/jamelaumn/myproject root 281104 0.0 2.3 31048 24280 pts/1 S+ 14:52 0:00 /home/jamelau mn/myproject/venv/bin/python venv/bin/gunicorn django_project.wsgi --bind 127.0. 0.1:8000 root 281105 0.0 4.1 52324 43716 pts/1 S+ 14:52 0:00 /home/jamelau mn/myproject/venv/bin/python venv/bin/gunicorn django_project.wsgi --bind 127.0. 0.1:8000 root 281193 0.0 0.1 … -
How to access drf(django rest framework) api in local network from different machine?
I deployed a drf api in apache server , when i access it from the same machine it work fine (get and post requests and also database connections all works good) , but when I try it from another machine in the same network i got two errors specially if it's a post request or there is a connection with database , the first one before sending anything it said "HTTP 405 Method Not Allowed" and if I try to send post requests it said "CSRF Failed: CSRF token missing or incorrect." and also if there is a get request has connections to database i got 500 server error . I tried to follow the documentation and also looked for these questions 1 , 2 but didn't help , actually I'm not even sure what cause these problems . Note : when i try just runserver command it works fine from other machines . here is virtual host and settings.py . virtual host: <VirtualHost 192.168.100.102:8001 _default_:8001> DocumentRoot /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject ServerAdmin yaz@gmail.com # Set the path to your Django project WSGIDaemonProcess myproject python-home=/opt/bitnami/projects/chatbotQZ/sources/env/ python-path=/opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject WSGIProcessGroup myproject WSGIScriptAlias / /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/myproject/wsgi.py # Configure access to static files Alias /static/ /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static <Directory /opt/bitnami/projects/chatbotQZ/sources/team_city/myproject/static> Require all … -
While Clicking On Razorpay Pay Now Using CARD / WALLET The New Tab Is about:blank#blocked , Django
I used to integrate django and razor pay , but when i click on pay now on options like , card , wallet , ( the payment needed to be in open in new tab ) the page become blank , i cannot access the success page Note: Upi is working and i am getting the result in dashboard , also payment id is generated and its reflecting in razorpay dash board Script Also Loaded My template .html <button id="rzp-button1" class="btn btn-primary my-2 w-100">Pay with Razorpay</button> <script> var options = { "key": "KEY", // Enter the Key ID generated from the Dashboard "amount": "{{payment.amount}}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "{{payment.id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 // "callback_url": "https://eneqd3r9zrjok.x.pipedream.net/", "prefill": { "name": "Gaurav Kumar", "email": "gaurav.kumar@example.com", "contact": "9000090000" }, "handler": function (response){ alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature) }, "notes": { "address": "Razorpay Corporate Office" }, "theme": { "color": "#3399cc" }, }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed', function (response){ alert(response.error.code); alert(response.error.description); alert(response.error.source); alert(response.error.step); alert(response.error.reason); alert(response.error.metadata.order_id); alert(response.error.metadata.payment_id); }); document.getElementById('rzp-button1').onclick = function(e){ … -
How to check if model has something inside in django?
I have a model of Branch, and a model of Worker. I want to filter only these branches, which have at least one user inside. models.py class Branch(models.Model): name = models.CharField(max_length=100) class Worker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=150) branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, related_name='branch') position = models.CharField(max_length=200) manager = models.BooleanField(default=False) I tried to add related_name to worker-branch, but now I don't know how to use it, and is it right way to do so? I also tried to filter like that: Worker.objects.filter(branch=?).exists(). But it doesn't make sense. At the end I want to have a list of branches which have at least one worker. -
Django. How to write the time to the database in UTC when using the settings 'TIME_ZONE' and 'USE_TZ = True'
There is a Django version 4.0 project. In it, in one of the tables, I use a field to save the datetime. I need the datetime stored in UTC in the database PostgreSQL. What I did: settings.py ... USE_TZ = True TIME_ZONE = "UTC+3" ... models.py class ManualMeasurements(models.Model): ... timestamp = models.DateTimeField(auto_now=False, auto_now_add=False, default=timezone.now) .... At the same time, migration to PostgreSQL created field with time zone: "timestamp" timestamptz NOT NULL Ok, but according to the documentation, this is enough so that in the form of the admin panel, the time in this field is displayed in the time field specified in settings.py , and the database was written in UTC. But no. I found that the database is currently written like this: 2023-07-10 14:55:17.000 +0300 In admin.py I'm overriding the save method: def save_model(self, request, obj: ManualMeasurements, form, change, debug=True): if obj.timestamp: obj.timestamp = obj.timestamp.astimezone(time_func.get_timezone('UTC')) super().save_model(request, obj, form, change) And still in the database I get the time in the current time zone with the time zone indication. What am I doing wrong and how do I get what I need? -
How to change the default language and add it_IT.UTF-8 locale to locale.gen on Azure?
I'm trying to change the default language on the Azure machine hosting my app. Currently, the default language is set to en_US.UTF-8 and is the only one in locale.gen, but I need to configure it to it_IT.UTF-8 to support my Django project. When I start my app and the Django app execute the "import locale" command followed by "locale.setlocale(locale.LC_TIME, 'it_IT.utf8')", I get the "unsupported locale setting" error. I suspect that the Italian language is not properly configured in the system. What are the necessary steps to change the default language and add the it_IT.UTF-8 locale to locale.gen on Azure? Or any others solution? Thank you in advance for your assistance! I created a startup.sh file in the home directory (the only persistent location) with the following commands: echo "it_IT.UTF-8" >> locale.gen locale-gen Then, in the Azure App configuration under General settings, I specified the path /home/startup.sh in Stack Settings > Startup Command. However, when I attempted to start the machine with this configuration, the startup failed for unknown reasons. I expected the startup.sh script to modify the locale.gen file and generate the it_IT.UTF-8 locale successfully. -
проблема в django. Проблема с кодировкой в uri [closed]
после деплоя Django проекта на хостинг. Слетает кодировка в киррилических url enter image description here во время get запроса не находит запись enter image description here На локальной машине все было нормально. На хостинге такая беда Не находит данные в бд. Из-за кода на киррилице -
Unexpected behavior of class method arguments [duplicate]
While writing the next unit test, I discovered the non-obvious behavior of the argument in the class method. The create_data method was supposed to create a dictionary with the default values of the arguments on each call. However, it turned out that if, after creating the dictionary, you change the value of one of the keys, then now IT will become default. from rest_framework.test import APITestCase class Test(APITestCase): def create_data(self, foo={'foo': 1}): return {'foo': foo} def test_1(self): default_data = self.create_data() print(default_data) # {'foo': {'foo': 1}} default_data['foo']['foo'] = 2 print(default_data) # {'foo': {'foo': 2}} def test_2(self): default_data = self.create_data() print(default_data) # {'foo': {'foo': 2}} Thus, after changing the value in the dictionary in the test_1 method, in the test_2 method, create_data will return a dictionary with the value that we set in test_1. Linter flake8 writes: Do not use mutable data structures for argument defaults. They are created during function definition time. All calls to the function reuse this one instance of that data structure, persisting changes between them. However, doesn't the line "All calls to the function reuse this one instance of that data structure" mean that each method call should use the original data structure written when the method … -
Sending email after Login Django Allauth
I’m new using Django Allauth, is there a way I can implement sending email after login? For example; every time someone logged into my account I will receive an email automatically. -
Django - Default schema (dbo) to custom schema name for native django apps?
I would like django to change the reference to the native django table(s) schema(dbo) as seen in the sql below. I have renamed the schema to meta in SQL, but when I run the app, it recreates the tables on the dbo schema again in the DB. So I deleted them again and renamed my meta schemas back to dbo in TSQL and tried to get django to migrate them to the new schema name by running, python manage.py inspectdb > models.py The models.py generates and then changing the following in the models.py file in the root folder. eg. class AuthGroup(models.Model): # model fields... class Meta: db_table = 'meta.auth_group' Then I run makemigrations and then migrate does not detect the models.py changes. Is this the correct approach or are we still stuck in changing the user running django to have a default schema to be set to "meta"? ALTER SCHEMA dbo TRANSFER [meta].[django_admin_log] ALTER SCHEMA dbo TRANSFER [meta].[admin_interface_theme] ALTER SCHEMA dbo TRANSFER [meta].[auth_group] ALTER SCHEMA dbo TRANSFER [meta].[auth_group_permissions] ALTER SCHEMA dbo TRANSFER [meta].[auth_user] ALTER SCHEMA dbo TRANSFER [meta].[auth_user_groups] ALTER SCHEMA dbo TRANSFER [meta].[auth_user_user_permissions] ALTER SCHEMA dbo TRANSFER [meta].[django_content_type] ALTER SCHEMA dbo TRANSFER [meta].[django_migrations] ALTER SCHEMA dbo TRANSFER [meta].[django_session] ALTER SCHEMA … -
Django how to display a pdf in canvas-wrapper
I have been given a task to make a page.inside it should be a Pdf that people can read without downloading if they don't want to. Now the problem is that meanwhile i can embed or Iframe the pdf i can not display it in way the template has been given to me Loading... <div class="spinner-grow text-primary" role="status"> <span class="visually-hidden">Loading...</span> </div> <div class="spinner-grow text-primary" role="status"> <span class="visually-hidden">Loading...</span> </div> </div> <canvas id="pdf-canvas" class="onload-pdf" data-url="{% static 'apply/pdf/terms.pdf' %}"> </canvas> </div> As you can see there is a canvas wrapper that pdf should be inside how can i do that?