Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my is the block content on django is displaying below the footer
this is the base.html the block content is between the header and the footer <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>header</h1> {% block content %} {% endblock content %} <h1>footer</h1> </body> </html> this is index that include the base html {% include "base.html" %} {% load static %} {% block content %} <p> body </p> {% endblock content %} the p tag boby should display in a middel expected output header body footer the outout header footer fghj the p tag should be in the middel right or is there something i missed? -
Join Our Exciting New Startup: Transform Business with Cutting-Edge IT Solutions
Are you a passionate developer looking to make an impact? We are a dynamic business consultation and implementation startup helping companies optimize their operations with customized software solutions, automation, and CRM tools. We’re looking for talented individuals to join our team on a profit-sharing basis, where your success is directly tied to the growth of the company. If you're looking for an opportunity to grow with a rapidly expanding startup and be part of innovative projects, this is the role for you! Positions Available: Frontend Developers Backend Developers Full Stack Developers Django Developers Custom Software Developers RPA Specialists CRM Specialists (Zoho, Salesforce, HubSpot) What We're Looking For: Frontend Developers: Expertise in HTML, CSS, JavaScript, and popular frameworks like React, Angular, or Vue.js. Backend Developers: Proficiency in Node.js, Python, Ruby, Java, or similar technologies. Full Stack Developers: A combination of both frontend and backend expertise with the ability to work on entire application stacks. Django Developers: Solid experience with Django for backend development, REST APIs, and integration with frontend frameworks. Custom Software Developers: Experience in creating bespoke solutions tailored to clients' needs, focusing on scalability and security. RPA Specialists: Expertise in automating business processes using tools like UiPath, Blue Prism, or … -
Django Function Update
I'm doing the update function but I get a message Page not found enter image description here views.py def detalle_tarea(request, tarea_id): if request.method == 'GET': tarea = get_object_or_404(Tarea, pk=tarea_id) form = TareaForm(instance=tarea) return render(request, 'tarea_detalles.html', {'tarea': tarea, 'form': form}) else: tarea = get_object_or_404(Tarea, pk=tarea_id) form = TareaForm(request.POST, instance=tarea) form.save() return redirect('tareas') url.py from django.contrib import admin from django.urls import path from tareas import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.inicio, name='inicio'), path('registrar/', views.registrar, name='registrar'), path('tareas/', views.tareas, name='tareas'), path('tareas/crear/', views.crear_tarea, name='crear_tarea'), path('tareas/<int:tarea_id>/', views.detalle_tarea, name='detalle_tarea') ] Any suggestion ??? -
How to get my favicon at `example.com/favicon.ico` in my Django project?
Google currently does not show my website's favicon in its search results and I learned that it is becuase it should be located at example.com/favicon.ico. I'm looking for a simple way to do this, hopefully without relying on redirects. I've used redirection to the version in my static folder but when I visit the url it redirects to example.com/static/favicon.ico, which I do not want. I want that if a user or a crawler visits example.com/favicon.ico they see my favicon. It is currently located at: my_project/ ├── my_project/ │ ├── ... │ ├── settings.py │ ├── ... ├── manage.py └── static/ └── img/ └── favicon.ico I use gunicorn as my web server and whitenoise as my http server. Here is my urls.py: from django.urls import path, include # new from django.contrib.sitemaps.views import sitemap # new from finder.views import ProcessorDetailSitemap, ArticleDetailSitemap, StaticViewSitemap # Correct import path #from django.conf import settings #from django.conf.urls.static import static sitemaps = { 'processor':ProcessorDetailSitemap, 'article': ArticleDetailSitemap, 'static': StaticViewSitemap, } urlpatterns = [ path('admin/', admin.site.urls), path('', include('finder.urls')), #new path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap",), ] It is also linked in my template usingn<link rel="icon" type="image/x-icon" href="{% static 'img/favicon.ico' %}"> -
Django view to PNG
I'm writing django webapp, and part of it is to generate view and convert it to png image. (any ideas other then below are appreciated). I've looked at some tools to convert "html to png", but there is mainly problem with {%static files and templates. Another approach is to render page using django templates in browser, and take screenshot. It can be done using "chromedriver" + selenium. I was able to do it in my local ubuntu. But on production - all I've got is remote (ssh) access to some linux bash, where my application is hosted. I've created venv, pip-installed selenium and (chromedriver-py or chromedriver-binary). For the second one - it looks like it is closer to start working, but I've got error message: SessionNotCreatedException Message: session not created: probably user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir Stackoverflow says, that I should somehow put there a path to my chrome installation's user dir, but is there any chrome installation in that console bash of mine? Any ideas how to move forward ? or any other ideas how to do it? My code: import chromedriver_binary def render_to_png(request ): … -
How to make Django's Browsable API Renderer generate correct URLs with an /api/ prefix when behind Nginx?
I'm deploying a Django application using the Django Rest Framework (DRF) on a server behind Nginx. The application is accessible via https://my-site.com/api/ where /api is routed to the Django application. However, when I access the API's browsable UI at https://my-site.com/api/locations, everything works fine. But when I try to click the "Get JSON" button from the UI, it generates an incorrect URL: /locations?format=json instead of the correct /api/locations?format=json. Or when i try to POST it posts to /locations instead of /api/locations The issue is that the DRF Browsable API Renderer seems to be constructing the URLs as if the app is running directly under the root path (/), but in reality, it's running under /api/ on the server due to Nginx routing. # Proxy requests to the Django backend (API) location /api/ { proxy_pass http://127.0.0.1:8000/; proxy_set_header X-Script-Name /api; # Tell Django it's running under /api 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-Proto $scheme; } What I'm Looking For: A solution to make the Django Browsable API Renderer correctly generate URLs with the /api/ prefix when behind Nginx. -
SessionStore object has no attribute 'get_session_cookie_age'
I have a Django project, everything goes well, but when I tried to handle the expiration of the session I got confused In a test view print(request.session.get_session_cookie_age()) give me this error SessionStore' object has no attribute get_session_cookie_age According to the documentation it should returns the value of the setting SESSION_COOKIE_AGE Trying debugging with this code : from django.contrib.sessions.models import Session sk = request.session.session_key s = Session.objects.get(pk=sk) pprint(s.get_decoded()) >>> {'_auth_user_backend': 'django.contrib.auth.backends.ModelBackend', '_auth_user_hash': '055c9b751ffcc6f3530337321e98f9e5e4b8a623', '_auth_user_id': '6', '_session_expiry': 3600} Here is the config : Version Django = 2.0 Python 3.6.9 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'drf_yasg', 'wkhtmltopdf', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] Thank's in advance -
Javascript fetch return 403 on Apache Server
Struggling with this issue for a few days now so any help is greatly appreciated. I managed to deploy my django project on a Linux server and it works fine apart from the model form submit. On the local development server it work fine and here is the workflow: User fills the form; User clicks submit; Javascript catches the submit event, submits a "POST" request and gets a response back; On the server side, the form is checked and if all is good an email is sent; HTML is updated to add the confirmation of form registration; Here is my code: home.html <div class="col-lg-8 offset-lg-2"> <form method="POST" class="row mt-17" id="form" onsubmit="return false"> {% csrf_token %} {% for field in form %} {% if field.name not in "message" %} <div class="col-12 col-sm-6"> <div class=form-group> <label for={{field.name}} class="form-label">{{ field.label }}</label> {{ field }} </div> </div> {% else %} <div class="col-12"> <div class=form-group> <label for={{field.name}} class="form-label">{{ field.label }}</label> {{ field }} </div> </div> {% endif %} {% endfor %} <div class="form-group mb-0"> <button type="submit" class="btn btn-primary btn-lg">Submit</button> </div> </form> </div> main.js const form = document.getElementById('form'); form.addEventListener("submit", submitHandler); function submitHandler(e) { e.preventDefault(); fetch("{% url 'messages-api' %}", { credentials: "include", method: 'POST', headers: { 'Content-Type': … -
can i save changes in the value before redis key expires
I could not find better solution. I have IDs and ranks in my Redis. Is it possible for me to save the changed ranks to the database before the Redis key expires?. can I trigger some function before it expires x time earlier -
CVAT OpenID Connect login doesn't show on Login page
I am trying to set up CVAT to support login using a custom IdP with OpenID Connect. I tried to make changes to base.py and docker-compose.override.yml to configure the server, but once I build and launch CVAT, nothing happens. I followed this guide, which was directly linked in the code. Here are the base.py changes: INSTALLED_APPS += ['cvat.socialaccount.providers.openid_connect',] ... SOCIALACCOUNT_PROVIDERS = { "openid_connect": { # Optional PKCE defaults to False, but may be required by your provider # Can be set globally, or per app (settings). 'OAUTH_PKCE_ENABLED': True, 'EMAIL_AUTHENTICATION' : True, "APPS": [ { "provider_id": "NAME", "name": "Service Name", "client_id": "client_id", "secret": "secret", "settings": { "server_url": "https://server/cvat/.well-known/openid-configuration", # Optional token endpoint authentication method. # May be one of "client_secret_basic", "client_secret_post" # If omitted, a method from the the server's # token auth methods list is used "token_auth_method": "client_secret_basic", "oauth_pkce_enabled": True, }, }, ] } } SOCIAL_AUTH_OPENIDCONNECT_KEY = 'client_id' SOCIAL_AUTH_OPENIDCONNECT_SECRET = 'secret' SOCIAL_AUTH_OPENIDCONNECT_API_URL = 'https://server/cvat/.well-known/openid-configuration' SOCIALACCOUNT_ONLY = True And this is the added docker-compose.override.yml file: services: cvat_server: environment: USE_ALLAUTH_SOCIAL_ACCOUNTS : true Since none of this worked, I tried creating a auth_config.yml as follows: --- social_account: enabled: true openid_connect: client_id: client_id client_secret: secret domain: https://server.it/ and told CVAT to use it by … -
Django Rest Framework login failure
I'm trying to make DRF work without custom serializers, views and urls, just using the default ones, but there is an issue with my login. Whenever i create a user on /api/v1/auth/register (this happens successfully) and then try to log in on /api/v1/auth/login, I get this error message: { "non_field_errors": [ "Unable to log in with provided credentials." ] } On the admin panel I login successfully with the same credentials, a proof they are correct. Even when I set up to use just the email as credentials, I am still required a password. Here is my settings.py: ... ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ ... 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'rest_framework_simplejwt', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', ] MIDDLEWARE = [ ... "allauth.account.middleware.AccountMiddleware", ] ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ) } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(hours=1), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } REST_AUTH = { "USE_JWT": True, "JWT_AUTH_COOKIE": "_auth", "JWT_AUTH_REFRESH_COOKIE": "_refresh", "JWT_AUTH_HTTPONLY": False, } SITE_ID = 1 ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_CONFIRM_EMAIL_ON_GET = True LOGIN_URL = "/api/v1/auth/login" I've tried many other approaches like custom user model, views and serializers, but it never worked, even became worse. I suppose there is something to … -
How to use uv run with Django in a PyCharm Docker environment?
I am developing a Django application using a Docker environment in PyCharm. Until now, I have been using pip for package management, but I am considering using uv to potentially reduce container build times. I managed to install uv in the Docker container, but I am unsure how to configure PyCharm to start Django development using uv run. It seems that the screen where I typically configure run/debug settings does not have an option for this. How can I set up uv run in PyCharm for my Django project? If possible, I would like to know the best practices or any alternative solutions for this setup. Thank you in advance for your help! -
How to integrate a Stripe Terminal Reader to POS application using Django?
I am developing a POS system using Django. I have a Stripe account, and through the system I am developing, I can process payments using credit or debit cards, with the money being deposited into my Stripe account. This is done by typing card information such as the card number, CVV, and expiration date. Now, I have decided to use a Stripe Terminal Reader to simplify the process. Instead of manually entering card details, customers can swipe, insert, or tap their card on the Terminal Reader for payment. The model I have ordered is the BBPOS WisePOS E. I powered it on, and it generated a code that I entered into my Stripe account. The terminal's online or offline status is displayed in my Stripe account. The idea is that when I select 'Debit or Credit Card' as the payment method, the amount to be paid should be sent to the terminal. However, this process is not working. The terminal still shows the screen displayed in the attached image." Let me know if you'd like further refinements! I don't know if I miss some steps that need to be done in order for this to work. Bellow are my functions: … -
Will django ORM always return tz aware timestamps in UTC
I have a simple model: class ExampleModel(models.Model): ts = models.DateTimeField() my settings.TIME_ZONE is set to Europe/Berlin When I add a row to examplemodel with tz aware ts field (13:00) I see in postgresql 12:00 in UTC - which is correct. When I read the same value using the same ExampleModel.objects.filter model object I obtain ts field 12:00 in UTC. Is it correct? I supposed it should be converted back to Berlin time, no? P.S. USE_TZ = True enabled. I do my tests in django console (./manage.py shell) -
Django with S3Boto3Storage - After upload, bucket didn't change
I'm using these configuration: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = '*****' AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = '****' AWS_DEFAULT_ACL = 'public-read' AWS_S3_FILE_OVERWRITE = False AWS_S3_ENDPOINT_URL = 'https://****' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_MEDIA_LOCATION = 'media' PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'{AWS_S3_ENDPOINT_URL}/{AWS_MEDIA_LOCATION}/ I change the photo on ADMIN, the URL is created, but when I see the bucket, nothing show to me. The URL didn't work for read, of course. I tried put access configuration on Digital Ocean Space Objects, but.. nothing work. -
Django ConnectionResetError: [Errno 54] Connection reset by peer
I'm trying to setup a project to send email from my local machine(MacOS) using django. But I see this error File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/ssl.py", line 1309, in do_handshake self._sslobj.do_handshake() ConnectionResetError: [Errno 54] Connection reset by peer This is code snippet that I have in my local. class EmailVerificationView(APIView): def post(self, request): smtp_server = "smtp-relay.brevo.com" smtp_port = 587 s = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=10) email = request.data.get('email') s.ehlo() s.login("login@email.com", "****") s.sendmail("test", email, 'Subject: verified') return Response({'message': 'Email sent successfully'}, status=status.HTTP_200_OK) I have tried few things as well, but nothing seems working. -
Getting Server Error (500) when setting debug to false due to manifest not including css files
I have an app that I've built using Django and React + Vite. Everything runs fine with Debug set to True, but once I set it to false I get a Server Error with the console output of: ValueError: Missing staticfiles manifest entry for 'reactjs/inspector-B1mMLMX5.css' The file reactjs/inspector-B1mMLMX5.css exists and is getting generated properly when running npm run build and the generated manifest file has an entry for it in the css property of the file that imports it: "Inspector/InspectorApp.jsx": { "file": "reactjs/inspector-FdX6WZL2.js", "name": "inspector", "src": "Inspector/InspectorApp.jsx", "isEntry": true, "imports": [ "_Loading-CnrJ4Xi6.js" ], "css": [ "reactjs/inspector-B1mMLMX5.css" ] }, It appears that with my current settings, running python manage.py collectstatic --noinput generates a separate manifest file called staticfiles.json, however this does not seem to be the issue as with some previous settings (i.e. not using WhiteNoise), I was getting the same error but referencing the correct Vite manifest file. Here is my current settings.py: """ Django settings for ChiroComp project. Generated by 'django-admin startproject' using Django 5.1.1. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ from pathlib import Path import os, sys, dj_database_url from dotenv import load_dotenv # Build … -
How can i solve? django - ValueError: ModelForm has no model class specified
i don't understand, what is the wrong. could you please let me know? which one do i need adjust? ValueError at /blog/15/ ModelForm has no model class specified. error messege picture which one do i need adjust? i want to know solve it blog/forms.py from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Mata: model = Comment fields = ("content", ) # exclude = ("post", "author", "created_at", "modified_at", ) blog/models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.author}::{self.content}" def get_absolute_url(self): return f"{self.post.get_absolute_url()}#comment-{self.pk}" blog/urls.py from django.urls import path from . import views urlpatterns = [ # FBV 방식의 패턴 # path('', views.index), # path('<int:pk>/', views.single_post_page) # CBV 방식의 패턴 path("", views.PostList.as_view()), path("<int:pk>/", views.PostDetail.as_view()), path("category/<str:slug>/", views.category_page), path("tag/<str:slug>/", views.tag_page), path("<int:pk>/new_comment/", views.new_comment), path("create_post/", views.PostCreate.as_view()), path("update_post/<int:pk>/", views.PostUpdate.as_view()) ] blog/views.py def new_comment(request, pk): if request.user.is_authenticated: post = get_object_or_404(Post, pk=pk) if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect(comment.get_absolute_url()) else: return redirect(post.get_absolute_url()) else: raise PermissionDenied -
How to extend a User's profile to save data in Django
I'm new to Django and I'm attempting to build a website where a user can view a DB of books and related authors and add any book to their 'favourites'. I've been searching lots and I can't find a satisfactory way of doing this - or indeed of saving any user data other than customising fields when you create a user. My current idea is to extend the UserModel to add an extra field which links their favourite book to the user. Tips on UserModel found here I can now see the UserProfile with some favourites by logging in to the Admin account, but I cannot link the View class/function with my bookfavs.html for the User to see their favourited books. The bookfavs.html states the username but not favourites. readable_project app_name = bookshelf #Models.py class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Book, related_name='favourites') class Author(models.Model): first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=30) dob = models.DateField() bio = models.CharField(max_length=300) def __str__(self): return self.first_name + " " + self.last_name def get_absolute_url(self): return reverse('authorlist') class Book(models.Model): id = models.AutoField(primary_key=True) users = models.ManyToManyField(User) title = models.CharField(max_length=50) num_page = models.IntegerField() date_pub = models.DateField() tags = models.CharField(max_length=200) blurb = models.CharField(max_length=300) def get_absolute_url(self): return reverse('')` #views.py #Add favourite button...? def favorite(request, … -
invalid_client when trying to authenticate with client_id and client_secret using django oauth toolkit and rest framework
I’m running a Django service that exposes endpoints via Django REST Framework. I want to secure these endpoints using Django OAuth Toolkit for authentication. When I create an application from the admin panel, I use the following settings: As shown in the screenshot, I disable client_secret hashing. With this configuration, everything works perfectly, and I can obtain an access token without any issues. * Preparing request to http://localhost:8000/o/token/ * Current time is 2024-12-19T10:47:03.573Z * Enable automatic URL encoding * Using default HTTP version * Enable timeout of 30000ms * Enable SSL validation * Found bundle for host localhost: 0x159f21ed0 [serially] * Can not multiplex, even if we wanted to! * Re-using existing connection! (#106) with host localhost * Connected to localhost (127.0.0.1) port 8000 (#106) > POST /o/token/ HTTP/1.1 > Host: localhost:8000 > User-Agent: insomnia/0.2.2 > Content-Type: application/x-www-form-urlencoded > Accept: application/x-www-form-urlencoded, application/json > Authorization: Basic MkVDdzAwWkN1cm1CRFc4TEFrSmpjSGt1bnh1OW9WZlRpY09DaGU5bDpKVTl6SURzd0Zob09JMzJhRjhUMVI2WnhYZDVVTU84TWwwbHdiZldNWFNxcHVuTGdsaXBLT2xLTFBNMTBublV1TGp3WGFWOVBPR2ZxYUpURzF5Smx2VGRMWHVPRzN0SVg4bE9tQ1N6U09lbTV4Z2ExaWZrNWRUdjVOYWdFV2djQQ== > Content-Length: 29 | grant_type=client_credentials * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Date: Thu, 19 Dec 2024 10:47:03 GMT < Server: WSGIServer/0.2 CPython/3.12.8 < Content-Type: application/json < Cache-Control: no-store < Pragma: no-cache < djdt-store-id: b377d48fbdae4db989aabb760af12619 < Server-Timing: TimerPanel_utime;dur=28.13699999999919;desc="User CPU time", TimerPanel_stime;dur=2.7200000000000557;desc="System CPU time", TimerPanel_total;dur=30.856999999999246;desc="Total CPU time", TimerPanel_total_time;dur=56.63733399705961;desc="Elapsed time", SQLPanel_sql_time;dur=5.738208987168036;desc="SQL … -
Reverse ForeignKey orm django
hi i am new to django orm , can some body help me i have data tables something like that class userprofile(models.model): foreignkey User related_name='fU' class A(models.model) foreignkey userprofile related_name='fa' Class b(models.model): forign key A related_name="fb" class C (models.model): foreignkey B related_name="fC" so what i am trying to achieve is , with User id i want to get information from all tables from top to bottom hierarchy . -
Why does updating to psycopg 3.x cause database timeouts?
I have a Django 5.x app. I've been using psycopg2, and I'm now trying to update to psycopg 3. This is pretty simple: I uninstalled everything to do with psycopg2 and installed psycopg[binary]. However, when I run my test suite now (in parallel), I am suddenly getting connection timeout expired and canceling statement due to statement timeout errors that I weren't getting before! My database configuration is pretty straightforward: STATEMENT_TIMEOUT = get_from_env( "POSTGRES_STATEMENT_TIMEOUT", default=30000, type_cast=int ) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": get_from_env("DB_NAME", "my-db"), "USER": get_from_env("DB_USERNAME", "my-db-user"), "PASSWORD": get_from_env("DB_PASSWORD", DEFAULT_DB_PASSWORD), "HOST": get_from_env("DB_HOSTNAME", "localhost"), "PORT": get_from_env("DB_PORT", "5432"), "OPTIONS": { "connect_timeout": 3, "options": f"-c statement_timeout={STATEMENT_TIMEOUT}ms", }, # Keep database connections open for 1 minute "CONN_MAX_AGE": 60, # But ensure that persistent connections are healthy before using them "CONN_HEALTH_CHECKS": True, }, } Is this configuration no longer valid with psycopg 3? Or are there some other changes in 3.x that could mean more timeouts? This is all using synchronous Python, no async or anything. -
RuntimeError: Model class modules.firebase-push-notifications.models.Notification doesn't declare an explicit app_label
error RuntimeError: Model class modules.firebase-push-notifications.models.Notification doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. for some reason i do not get this error when i try run manage.py runserver but if i use vscode debugger, this error shows up the debugger was working fine, this error popped up randomly setting.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites" ] LOCAL_APPS = [ 'home', 'users.apps.UsersConfig', 'chat.apps.ChatConfig', 'admin_panel.apps.AdminPanelConfig', ] -
Retrieve exect previous or next occurrence of a recurring event from Google Calendar
I have a recurring event in Google Calendar, and I need to fetch either the previous and next occurrence of this event, based on a given event ID. Specifically, I want to retrieve the event details for the exact occurrence before or after the specified recurring event ID. How can I use the Google Calendar API to get the exact details for the previous or next recurrence of a given event, considering its recurrence rule (e.g., daily, weekly, etc.)? I attempted to use the Google Calendar API to fetch the details of the previous or next occurrence of a recurring event, using the event ID and its recurrence rule. I expected to retrieve the exact details for the previous or next occurrence based on the recurrence pattern (e.g., daily, weekly, etc.). However, I wasn't able to correctly retrieve the previous or next event occurrence. Instead, the API only returned the original event or no matching results at all. this is my code def fetch_event_by_id(service, event_id,future,past): if future or past: pass # here i want to pass ,exect future or past one event detail, without giving timeMin and timeMax,here future and past is the number of future and past event, else: … -
Django + ODBC Driver 17 for SQL Server: Raw query can't process list or tuple arguments
Code I wrote a function that wraps Django's standard processing for raw SQL queries. def run_mssql_query(query, connection="prod", args=None): """Method will run query on MSSQL database Args: query (str): MSSQL Query connection (str): Which connection to use. Defaults to "prod". Returns: dict: Results of query """ if connection == "omron": results = {} conn = get_oracle_connection() with conn.cursor() as cursor: try: if args == None: args = dict() cursor.execute(query, args) cursor.rowfactory = lambda *args: dict(zip([d[0] for d in cursor.description], args)) results = cursor.fetchall() except: results = {} return results with connections[connection].cursor() as cursor: if args == None: args = list() cursor.execute(query, args) # Replace with your actual query try: columns = [col[0] for col in cursor.description] results = [dict(zip(columns, row)) for row in cursor.fetchall()] except: results = {} return results Execution looks something like this: data = run_mssql_query(f"""SELECT * FROM EVENTS.dbo.MES_BARCODES WHERE BARCODE = %s""", args=["123"]) Problem When i'm using string, int, etc..., it's working like a charm, but when i'm tring to pass list to the params of my params, like this (for example): barcodes = ["123", "321"] data = run_mssql_query(f"""SELECT * FROM EVENTS.dbo.MES_BARCODES WHERE BARCODE IN %s""", args=[list(barcodes)]) It's giving me this error: ('42000', '[42000] [Microsoft][ODBC Driver 17 for …