Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm trying to move from development to production with Gunicorn and Nginx with Django, but my 'static' files are not loading. Please help me
Hi everyone, I've been having issues with Gunicorn and Nginx — the latter is not loading my 'static' files. Please help, I've been stuck on this for a week and I don't know what's going on. The 'static' files are not loading. This is my 'settings.py' file. This is the Nginx configuration This is my 'urls.py' -
What should be the best practice for handling migration files in Django when multiple developers are involved?
I have a question regarding Django migration files and version control. When I run migration commands in Django python manage.py makemigrations and python manage.py migrate, files such as 0001_initial.py are created. I've come across differing opinions online about whether migration files should be committed to Git or added to .gitignore. Some suggest ignoring them, while others recommend committing them and squashing when necessary. Could someone explain the scenarios that arise when multiple developers commit migration files, what issues or errors might occur, and how we can avoid these problems in a collaborative environment? I am new to Django. Thanks -
post() missing 1 required positional argument: 'slug'
I'm facing a problem in my Django project, and I need your help. When I try to access the view that handles requests to the post page, I get the following error: post() missing 1 required positional argument: 'slug' This happens when I try to navigate to a URL that should handle viewing a specific post. I have determined the route in urls.py , which takes the slug parameter, and it looks like this: path('post//', post, name='post'), In my post view, I expect to accept this parameter, but it looks like it is not being passed properly. I would really appreciate any help or advice. My models.py: from django.db import models from django.utils.text import slugify from django.contrib.auth import get_user_model from django_resized import ResizedImageField from tinymce.models import HTMLField from hitcount.models import HitCountMixin, HitCount from django.contrib.contenttypes.fields import GenericRelation from taggit.managers import TaggableManager from django.shortcuts import reverse User= get_user_model() class Author(models.Model): user =models.ForeignKey(User,on_delete=models.CASCADE) fullname = models.CharField(max_length=40,blank=True) slug = slug = models.SlugField(max_length=400,unique=True,blank=True) bio = models.TextField(HTMLField) points = models.IntegerField(default=0) profile_pic = ResizedImageField(size=[50,80],quality=100,upload_to='authors',default=None,null=True,blank=True) def __str__(self): return self.fullname def save(self,*args,**kwargs): if not self.slug: self.slug = slugify(self.fullname) super(Author,self).save(*args, **kwargs) class Category(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=400,unique=True,blank=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.title def save(self,*args,**kwargs): … -
Error connect with Cloud SQL, Cloud Run and Django
I have an application running on Django in Cloud Run that connects to a PostgreSQL database hosted on Cloud SQL. It is currently working and configured as follows: DATABASES = {'default': env.db()} DATABASES['default']['OPTIONS'] = { 'pool': { 'min_size': 5, 'max_size': 20 } } This configuration works, but the active connections remain high. When I remove the pool configuration, I end up getting several errors. 2025/04/12 16:24:15 Cloud SQL connection failed. Please see https://cloud.google.com/sql/docs/mysql/connect-run for additional details: failed to get instance: Refresh error: failed to get instance metadata (connection name = "xxx"): googleapi: Error 429: Quota exceeded for quota metric 'Connect Queries' and limit 'Connect Queries per minute per user per region' of service 'sqladmin.googleapis.com' for consumer 'xxx'. Even after configuring CONN_MAX_AGE, it keeps throwing errors. I’ve tried setting up pgBouncer, but was unsuccessful due to needing permissions that are impossible to access on Cloud SQL. Lastly, I’m running Django in the following way: WEB_CONCURRENCY=${WEB_CONCURRENCY:-4} THREADS=${THREADS:-8} exec /usr/local/bin/gunicorn project.asgi:application \ --bind "0.0.0.0:$PORT" \ --workers "$WEB_CONCURRENCY" \ --worker-class uvicorn.workers.UvicornWorker \ --threads "$THREADS" \ --timeout 0 Has anyone ever faced something similar or has a solution for this? -
Migrations is not working for this model in my project
I have create multiple models in Django project but this model migration is not working in my project can anybody give me the reason for tis problem and how to fix this. models.py class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) avatar=models.ImageField(upload_to='avatar/',blank=True,null=True) def __str__(self): return f"{self.user.email}" running migrations output is no change in Migration -
Infinite redirection loop for Django backend (hosted on railway) application (hosted on cloudfare)
tl;dr I'm getting an infinite loop when I request my django backend, and I don't know how to fix it I'll give some context to what's happening: My django backend works on localhost (I used nginx as a reverse proxy when developing it) I've got a cloudfare domain, and I've registered by backend to it on railway when I try to connect to the backend over the Cloudflare domain, I keep getting redirected to the page I requested- so it's an infinite loop I'll give some outputs to show what's happening Request headers: Request URL: https:... <--- my project domain Request Method: GET Status Code: 301 Moved Permanently Remote Address: x.x.x.x:443 Referrer Policy: strict-origin-when-cross-origin And the response: alt-svc: h3=":443"; ma=86400 cf-cache-status: DYNAMIC cf-ray: 92efc2dfbffc57dd-SYD content-type: text/html; charset=utf-8 date: Sat, 12 Apr 2025 03:50:44 GMT location: ... <--- same domain name as I requested nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800} report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=BY0YmE3vW8uxgXBlVKUb%2BBuxQrbGw%2F2J2wEGzGndoKueBiCzA%2FYkGsADUkrcMq6KC02ocvzetSIzDhSun56YdCECv04ANU3UaaxEzBQ6%2BnNfN9r5tmjhDD53DHq3IPVCnWnwPw%3D%3D"}],"group":"cf-nel","max_age":604800} server: cloudflare server-timing: cfL4;desc="?proto=QUIC&rtt=8014&min_rtt=7349&rtt_var=1550&sent=12&recv=11&lost=0&retrans=0&sent_bytes=3715&recv_bytes=3440&delivery_rate=821&cwnd=12000&unsent_bytes=0&cid=b1e2e4808802a704&ts=2802&x=16" x-railway-edge: railway/us-west2 x-railway-request-id: hd3fL70KS824dNgkcC4bnQ_3336177264 This request and response keep happening until the browser steps in. If I curl the endpoint, I just get: <a href="my backend domain">Moved Permanently</a>. So Cloudflare has the flexible SSL/TLS encryption mode, and in my settings.py, I have: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = False … -
Problem with Layout of my personal website, i using Django and JavaScript in this project
base.html <body> {% block content %} {% endblock %} {% block js %} {% endblock %} </body> base.css * { margin: 0; padding: 0; box-sizing: border-box; } html, body { font-size: 62.5%; scroll-behavior: smooth; } body { display: flex; align-items: center; justify-content: center; flex-direction: column; } navbar.html <header id="header"> <nav id="navbar"> <div class="photo-name"> <img id="photo" src="{% static 'images/perfil.png' %}" alt="foto-perfil" /> <h1>Gabriel Gattini</h1> <div class="line"></div> <p class="p-dev">{% trans "Desenvolvedor Full Stack" %}</p> </div> <div class="container-nav-links"> <div class="projects"> <a class="a-nav" href="#projects">{% trans "Projetos" %}</a> <i id="icon" class="fa-solid fa-laptop-code"></i> </div> <div class="aboutme"> <a class="a-nav" href="#aboutme">{% trans "Sobre Mim" %}</a> <i id="icon" class="fa-solid fa-book-open-reader"></i> </div> <div class="tools"> <a class="a-nav" href="#skills">{% trans "Habilidades" %}</a> <i id="icon" class="fa-solid fa-fire"></i> </div> <div class="contacts"> <a class="a-nav" href="#contacts">{% trans "Contato" %}</a> <i id="icon" class="fa-solid fa-at"></i> </div> <div class="background-color"> <i id="sun-icon" class="fa-solid fa-sun"></i> <i id="moon-icon" class="fa-solid fa-moon"></i> </div> <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.get_full_path }}"> <button class="nav-btn" type="submit" name="language" value="pt-br"> <img id="brazil" src="{% static 'images/brasil.svg' %}" alt="flag-brasil" /> </button> <button class="nav-btn" type="submit" name="language" value="en"> <img id="eua" src="{% static 'images/eua.svg' %}" alt="flag-eua" /> </button> </form> </div> </nav> </header> navbar.css #header { z-index: 1; position: fixed; height: 100vh; width: 20%; left: 0; top: … -
Optimizing Django ORM for Hybrid Queries (PostgreSQL + Vector Similarity Search)
I'm implementing a RAG (Retrieval-Augmented Generation) system that requires combining traditional Django ORM filtering with vector similarity searches. The specific workflow needs to: First filter products by standard relational fields (e.g., category="books") Then perform vector similarity search on just that filtered subset of product descriptions Current Implementation and Challenges: # Current inefficient approach (two separate operations) books = Product.objects.filter(category="books") # Initial DB query vectors = get_embeddings([b.description for b in books]) # Expensive embedding generation results = faiss_search(vectors, query_embedding) # Vector search Key problems with this approach: Requires loading all filtered records into memory Makes two separate passes over the data Doesn't leverage PostgreSQL's native capabilities when using pgvector What I've Tried: Raw SQL with pgvector: query = """ SELECT id FROM products WHERE category = 'books' ORDER BY description_embedding <=> %s LIMIT 10 """ results = Product.objects.raw(query, [query_embedding]) Problem: Loses Django ORM benefits like chaining, model methods. django-pgvector extension: from pgvector.django import L2Distance books = Product.objects.annotate( distance=L2Distance('description_embedding', query_embedding) ).filter(category="books").order_by('distance')[:10] Problem: Doesn't scale well with complex filter conditions Expected Solution: Looking for a way to: Maintain Django ORM's expressiveness for initial filtering. Efficiently combine with vector search on the filtered subset. Avoid loading all records into memory. Preferably stay within Django's … -
Can not preview s3 bucket images in django admin
I'm uploading images to s3 bucket from django adimin (image field). However, when I try to preview image in the admin its not showing with following error. I added configured dajngo-csp and added the s3 domain to allow requests. But still image is broken. I can right click on image placeholder and view it anyway. Here are my settings.py entries: INSTALLED_APPS = [ ... "csp", ] MIDDLEWARE = [ ... "csp.middleware.CSPMiddleware", ] from csp.constants import SELF CONTENT_SECURITY_POLICY = { "DIRECTIVES": { "default-src": [SELF], "img-src": [SELF, "s3.eu-central-1.amazonaws.com"], } } Browser error: Content-Security-Policy: The page’s settings blocked the loading of a resource (img-src) at https://s3.eu-central-1.amazonaws.com/xxx/media/xxx/xxx.png because it violates the following directive: “default-src 'self'” -
Django's StatReloader returning error but server runs (although all requests written in red in the console)
I run python manage.py runserver in a folder (which worked finely yesterday) and get python : Watching for file changes with StatReloader Au caractère Ligne:1 : 1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Watching for fi...th StatReloader:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError but the server seems to work all the same even if requests are written in red in the console. I've tried what's advised here but nothing changes. I'm on Windows Powershell. -
why does this error in Template syntax keep coming for a django file?
I am new to python and I am working on a project. I completed the entire project but this error is not getting fixed. attaching the error and the code where there is error. this is the error TemplateSyntaxError at /meeting/ Invalid block tag on line 13: 'static'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/meeting/ Django Version: 5.2 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 13: 'static'. Did you forget to register or load this tag? Exception Location: D:\django-video-chat\venv\Lib\site-packages\django\template\base.py, line 577, in invalid_block_tag Raised during: chat.views.room Python Executable: D:\django-video-chat\venv\Scripts\python.exe Python Version: 3.12.8 code where there is error Can someone please help. -
International Phone Number Widget in Django Model Form
I am trying to include International code for the phone number, so users like easily select the country code from the drop down menu. I am following this example https://www.youtube.com/watch?v=Q5UPMEA5fX0 , but getting MultiWidget error. Here is how my ModelForm looks. Here is what the error looks like. It says I am missing 'widgets' argument. I am not able to find any examples online. Any help would be appreciated. -
Running Django tests ends with MigrationSchemaMissing exception
I'm writing because I have a big problem. Well, I have a project in Django where I am using django-tenants. Unfortunately, I can't run any tests as these end up with the following error when calling migrations: ‘django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in LINE 1: CREATE TABLE ‘django_migrations’ (‘id’ bigint NOT NULL PRIMA...’ The problem is quite acute. I am fed up with regression errors and would like to write tests for the code. I will appreciate any suggestion. If you have any suggestions for improvements to the project, I'd love to read about that too. Project details below. Best regards Dependencies [tool.poetry.dependencies] python = "^3.13" django = "5.1.8" # The newest version is not compatible with django-tenants yet django-tenants = "^3.7.0" dj-database-url = "^2.3.0" django-bootstrap5 = "^25.1" django-bootstrap-icons = "^0.9.0" uvicorn = "^0.34.0" uvicorn-worker = "^0.3.0" gunicorn = "^23.0.0" whitenoise = "^6.8.2" encrypt-decrypt-fields = "^1.3.6" django-bootstrap-modal-forms = "^3.0.5" django-model-utils = "^5.0.0" werkzeug = "^3.1.3" tzdata = "^2025.2" pytz = "^2025.2" psycopg = {extras = ["binary", "pool"], version = "^3.2.4"} django-colorfield = "^0.13.0" sentry-sdk = {extras = ["django"], version = "^2.25.1"} Settings.py import os from pathlib import Path from uuid import … -
Unable to open nginx with domain and can't open checkmk in Firefox browser
So I'm unable to open nginx with my domain name, arborhub.io and I can't open checkmk on the browser either. I decided to try & run checkmk behind nginx instead of apache, which I did successfully. I was hoping to fix the issue of the conflict between apache (checkmk) and nginx. But I still can't open either programs in my Firefox browser. I initially assumed my Django was causing this 502 gateway page error, but my Django server is running fine. Also my nginx is running with no problems either with `sudo sDoing 'status' on site arborhub: agent-receiver: running mkeventd: running rrdcached: running npcd: running nagios: running apache: running redis: running crontab: running Overall state: running ystemctl reload nginx` ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: en> Active: active (running) since Wed 2025-04-09 20:03:09 MDT; 3h 49min ago Invocation: 5e827ca7649a43b8bd078f49a64d7c77 Docs: man:nginx(8) Process: 10356 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_proc> Process: 10360 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (> Process: 15562 ExecReload=/usr/sbin/nginx -g daemon on; master_process on; > Main PID: 10361 (nginx) Tasks: 5 (limit: 18232) Memory: 4.4M (peak: 8.4M) CPU: 85ms CGroup: /system.slice/nginx.service ├─10361 "nginx: master process … -
Django unable to read "static" folder even though its available
It might look like a duplicate question but I read and tried various solutions and its not working for me. I'm using MAC OS and running venv with Django5. Getting error stating the "STATICFILES_DIRS setting does not exist.". The error output is as follows: Desktop/Projects/Django/moviestore/moviesstore/static' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. April 10, 2025 - 02:45:10 Django version 5.0, using settings 'moviestore.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = "**********" DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "home" ] 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", ] ROOT_URLCONF = "moviestore.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'moviesstore/templates')], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "moviestore.wsgi.application" DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { … -
What is Python mostly used for in websites, and are there common issues?
I'm learning web development and I'm curious about how Python is used when it comes to websites. I know languages like HTML, CSS, and JavaScript are used on the front end, but where does Python come in? I’d like to understand: What part of a website Python is mostly used for Common Python frameworks for web development Any typical issues or challenges developers face when using Python for websites Any insights or examples would be appreciated! -
@login_required depending on setting?
While I expected this to be answered somewhere on StackOverflow, I haven't found it, so I apologise if this is a dupe. I want a setting to control whether certain views require a user to be logged in. If the setting is turned on, I want the views to behave as if they were decorated with @login_required, i.e. after the user logs in, they should be redirected back to the view. I don't mind putting code in the view to check the setting and calling redirect("account_login") if it's turned on. And, I suppose, passing request.get_full_path() as the next parameter would probably work. But redirecting to login and back seems a common enough use case for me to expect some elegant function in django.contrib.auth or django-allauth to do it, or that it would be easy to roll my own conditional @login_required decorator. Am I missing something? Thanks. -
Playwright's set_input_files() function doesn't work properly in python
I'm writing tests for my Django project using playwright and StaticLiveServerTestCase. In one test I need to choose two files using input[type=file] field and send them to the server. file_input = page.locator('input[type="file"]') file_input.set_input_files(["Input1.xlsx", "Input2.xlsx"]) But Playwright sending only first file and my test fails. I've tried to watch does input field has only one file, but it has both of them inside after choosing file_info = page.evaluate(""" element => { const files = Array.from(element.files); return files.map(file => ({ name: file.name, size: file.size, type: file.type })); } """, file_input.element_handle()) print("Files that JS sees:", file_info) That is the output: Files that JS sees: [{'name': 'Input1.xlsx', 'size': 5853, 'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}, {'name': 'Input2.xlsx', 'size': 5851, 'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}] And Playwright outs only the first: input_value = file_input.input_value() print("Playwright's version:", input_value) Playwright's version: C:\fakepath\Input1.xlsx If you'll ask me I've tried absolute path for files and I've tried to change browsers. I've tried to test it manually and hadn't this problem. Django version 5.1.6 Playwright version 1.51.0 -
Django/Heroku error "Web process failed to bind to $PORT"
I am trying to configure a Django/PostgreSQL project to deploy on Heroku using Waitress. (I've only done this once successfully, several years ago using Guincorn). I am ultimately running into an error Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch The full error log is: 2025-04-09T07:09:48.289599+00:00 heroku[web.1]: State changed from crashed to starting 2025-04-09T07:09:52.235046+00:00 heroku[web.1]: Starting process with command `waitress-serve project.wsgi:application` 2025-04-09T07:09:52.781389+00:00 app[web.1]: Python buildpack: Detected 512 MB available memory and 8 CPU cores. 2025-04-09T07:09:52.781847+00:00 app[web.1]: Python buildpack: Defaulting WEB_CONCURRENCY to 2 based on the available memory. 2025-04-09T07:09:53.244456+00:00 app[web.1]: INFO:waitress:Serving on http://0.0.0.0:8080 2025-04-09T07:10:52.357945+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch 2025-04-09T07:10:52.370446+00:00 heroku[web.1]: Stopping process with SIGKILL 2025-04-09T07:10:52.421789+00:00 heroku[web.1]: Process exited with status 137 2025-04-09T07:10:52.445044+00:00 heroku[web.1]: State changed from starting to crashed" I initially thought this was a issue with defining PORT, but after leaving it out of my Procfile, it seems like Heroku is designating PORT locally, and so that problem may be resolved? I'm hoping someone might have some ideas that might cause "failed to bind to $PORT." Could it be an issue with DATABASE_URL? I am using Heroku's … -
What is best way to store small amount of data in BE (literally 1 line)?
I am currently working on functionality where users wants to keep a single message in header of a page to notify others of something happening in system. Essentially a header that can be updated by any user. As this header needs to be shown to every user in site I can't store it in local storage or user's table. Also this is a single line of message on a single page, so making a whole database table for this sounds utterly stupid. So to achieve this functionality for now I have added a json file in BE which just have this message in there and a view which allows users to edit this file. I have also placed this file in gitignore because data change in this should not reflect in git. This system works fine for now, but when I redeploy using Docker this file is removed and rebuilt losing the initial message. Is there a better way to store and update this data? Or any way to not lose my data on redeploy? userdata.json { message: "Holiday tomorrow, please report any issues by 3." } Reading data in Django View try: if not os.path.exists(USERDATA_FILE): # Create the file … -
Can't establish connection between web socket and server
I'm writing a chat app using django channels, redis and daphne. When I try to submit the message and tap on the button I have GET query, but I've written js in my html file and it has to prevent standart behaviour of this form. I don't know why doesn't it establish the connection and just send GET query, what's wrong here? I've checked redis server, It works. I've installed all required modules, I've checked It with gpt, nothing helps. How to make it establish the connection? consumer.py: import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from django.apps import apps class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.chat_name = self.scope['url_route']['kwargs']['chat_name'] await self.channel_layer.group_add(self.chat_name, self.channel_name) await self.accept() @database_sync_to_async def save_message(self, text_data): Chat = apps.get_model('chat', 'Chat') ChatMessage = apps.get_model('chat', 'ChatMessage') User = apps.get_model('auth', 'User') chat = Chat.objects.get(chat_name=text_data['chat_name']) sender = User.objects.get(username=text_data['sender']) ChatMessage.objects.create( chat=chat, body=text_data['message'], sender = sender, ) async def receive(self, text_data): print('Received from frontend:', text_data) data_json = json.loads(text_data) await self.save_message(data_json) event = {"type": "send_chat_message", "message": data_json} await self.channel_layer.group_send(self.chat_name, event) async def send_chat_message(self, event): await self.send(text_data=json.dumps({"message": event["message"]})) chat.html: {% extends "base.html" %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chat</title> </head> <body> {% block content %} <div class="container"> <h2>Chat with … -
Quiero usar el usuario que esta logueado en mi modelo de wagtail
Hola a todos primero que nada muchas gracias de antemano tengo este problema: Estoy haciendo una página de blog con wagtail y me gustaria que le autor fuera el usuario que esta logueado pero e intentado de mil maneras y nada me funciona siempre el usuario es None class BlogPage(Page): autor = models.CharField(max_length=255) Como mencione antes quiero que ese campo sea el usuario logueado en el admin de wagtail. Mi idea era usar request pero al parecer no funciona con wagtail -
pytz library timezone conversion issue
I am trying to work with django and converting timezones between UTC and my timezone ("America/Winnipeg"), but I keep running into issues and I think there might be a bug. Here is my code: #UTC to "America/Winnipeg" utc1 = datetime.datetime(2025,4,8,12,00) utc1 = utc1.replace(tzinfo = pytz.utc) utc2wpg = utc1.astimezone(pytz.timezone("America/Winnipeg")) wpgb2utc = utc2wpg.astimezone(pytz.utc) print(f"UTC Time: {utc1}") print(f"UTC to Winnipeg Time: {utc2wpg}") print(f"Winnipeg back to UTC Time: {wpgb2utc}") #America/Winnipeg to UTC wpg1 = datetime.datetime(2025,4,8,7,0) wpg1 = wpg1.replace(tzinfo = pytz.timezone("America/Winnipeg")) wpg2utc = wpg1.astimezone(pytz.utc) utcb2wpg = wpg2utc.astimezone(pytz.timezone("America/Winnipeg")) print(f"Winnipeg Time: {wpg1}") print(f"Winnipeg to UTC Time: {wpg2utc}") print(f"UTC back to Winnipeg Time: {utcb2wpg}") When you run the UTC to "America/Winnipeg" block, you get the output: UTC Time: 2025-04-08 12:00:00+00:00 UTC to Winnipeg Time: 2025-04-08 07:00:00-05:00 Winnipeg back to UTC Time: 2025-04-08 12:00:00+00:00 But when you run the exact same timezone converting back from Winnipeg to UTC, you get this output: Winnipeg Time: 2025-04-08 07:00:00-06:29 Winnipeg to UTC Time: 2025-04-08 13:29:00+00:00 UTC back to Winnipeg Time: 2025-04-08 08:29:00-05:00 There is clearly a discrepancy in the timezone conversions. Is there an issue with my code or is there an issue with the pytz library's conversion. Are you having the same output? Btw I am using Python 3.13 -
unresponsive boostrap on google chrome from my django app
Here is my app directory Here is the head of my html `{% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> Asoro Auto </title> <link href=" {% static 'Dashboard/css/bootstrap.min.css'% }" rel="Stylesheet" > </head>` Here is the body that contains tags styled according to bootstrap convention `<div class="container"> <div class="row"> <div class="col">AB2C1D1 </div> <div class="col">AB2C1D2 </div> <div class="col">AB2C1D3 </div> <div class="col">AB2C1D4 </div> </div> <div class="row">AB2C2 </div> <div class="row">AB2C3 </div> <div class="row">AB2C4 </div> </div>` Here is the bootstrap script added before the end of my html body tag `<script src=" {% static 'Dashboard/js/bootstrap.min.js'% }"></script> </body>` In my settings.py here are my some necessary configurations highlighted for the local twitter bootstrap to work `STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR/"static",` ] -
Django with a single db raises "the current database router prevents this relation" when intializing model
In django I have the following database models: ParentA ParentB Connector which has a foreign key that references the model ParentA and a foreign key that references the model ParentB The Connector model: from django.db import models class Connector(models.Model): class Meta: ordering = ["parent_a"] unique_together = (("parent_a", "parent_b"),) parent_a = models.ForeignKey( ParentA, on_delete=models.CASCADE, related_name="connected_bs", ) parent_b = models.ForeignKey( ParentB, on_delete=models.CASCADE, related_name="connected_as", ) In my code each time a ParentA objects gets created I am finding which existing ParentB objects can get connected with it and I am creating Connector objects with the code that follows. The function that creates the Connector objects is a method of the ParentA, so self here is a ParentA object from django.db import models class ParentA(models.Model): ... def create_connectors(self): matching_p_b_objects = self.__get_matching_parent_b_objects() new_matching_p_b_objects = matching_p_b_objects.filter(~Q(connected_as__parent_a=self)) Connector.objects.bulk_create( [ Connector(parent_a=self, parent_b=parent_b) for parent_b in new_matching_p_b_objects ] ) The function is called all the time and it mostly works but some times it randomly throws the error File "/code/backend/app/models/parent_a.py", line 989, in create_connectors [ File "/code/backend/app/models/parent_a.py", line 990, in <listcomp> Connector(parent_a=self, parent_b=parent_b) File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 541, in __init__ _setattr(self, field.name, rel_obj) File "/usr/local/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 254, in __set__ raise ValueError( ValueError: Cannot assign "<ParentA: 340459>": the current database router …