Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing efficient data history/versioning in django + postgres
I'm trying to track changes to persisted data in a django + postgresql stack by saving operations on rows and 'replaying' events from the beginning (or a smaller number of snapshots) to restore an arbitrary past version. After some research I'm pretty sure I want this to be done via postgresql triggers and that one should store the pg_current_xact_id() value to get a logical order of transactions (is the latter correct?). Looking around for libraries that do this, django-pghistory seems perfect for this, but upon inspection of the data structures this library only stores UUIDs and timestamps. The former is not ordered and the latter seems prone to race conditions since two parallel transactions can start at the same time (within clock precision). Am I missing something here? Additionally, I find it essential for performance to save a full snapshot of an object/table after a large number of changes so that the execution time to jump to a specific version does not deteriorate with many changes. However, none of the available solutions I found seem to be doing this. Am I missing something here? Is the performance negligible for most applications? Do people start rolling their own version when it … -
How to prevent user from modifying data through Django DRF
My API endpoints are exposed to the browser via Django DRF which I'm aware is normal. However, the primary issue with this is that someone can perform any operation my API can perform without going through my application. I have validation for my endpoints but the user could delete payment records, for example, or POST invalid data, and other similar operations. I am using JWT auth but if the user is already logged in my application in the same browser they can see it. Is there any way to prevent this? -
Installing Django with Pythonista and Stash gets errors : name 'sys' is not defined with « import sys » in script
I try to install Django with the Pythonista 3.4 on Ipad Pro (M4) with Stash (after running launch_stash.py): [~/Documents]$ pip install django And I have these errors: site-packages/stash/bin/pip.py:35: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives from distutils.util import convert_path Querying PyPI ... Downloading package ... Opening: https://files.pythonhosted.org/packages/63/e0/6a5b5ea350c5bd63fe94b05e4c146c18facb51229d9dee42aa39f9fc2214/Django-5.2-py3-none-any.whl Save as: /private/var/mobile/Containers/Data/Application/31B610E4-119A-4907-8E17-35502B9C7701/tmp//Django-5.2-py3-none-any.whl (8301361 bytes) [====================] 100.00% | 7.9MiB stash: ^C KeyboardInterrupt: Exit: 0 Installing wheel: Django-5.2-py3-none-any.whl... stash: <class 'NameError'>: name 'sys' is not defined I already have import sys in my launch_stash.py I tried to add import sys in console AFTER running launch_stash.py with import sys inside. Also, I tried to force the different versions of django to install. I still have the errors : [~/Documents]$ pip install django Querying PyPI ... Downloading package ... Opening: https://files.pythonhosted.org/packages/63/e0/6a5b5ea350c5bd63fe94b05e4c146c18facb51229d9dee42aa39f9fc2214/Django-5.2-py3-none-any.whl Save as: /private/var/mobile/Containers/Data/Application/31B610E4-119A-4907-8E17-35502B9C7701/tmp//Django-5.2-py3-none-any.whl (8301361 bytes) [====================] 100.00% | 7.9MiB stash: ^C KeyboardInterrupt: Exit: 0 Error: failed to download package from https://files.pythonhosted.org/packages/63/e0/6a5b5ea350c5bd63fe94b05e4c146c18facb51229d9dee42aa39f9fc2214/Django-5.2-py3-none-any.whl stash: ^C KeyboardInterrupt: Exit: 1 Also I have this annoying error : stash: ^C KeyboardInterrupt: Exit: 1 It appears first time just after running launch_stash.py: stash: ^C KeyboardInterrupt: Exit: 0 StaSh v0.7.5 on python 3.10.4 Warning: you are running … -
Can`t connect Digital Ocean Spaces with Django, when i upload a file instead of saving it on DO it creates new folder locally
I'm trying to configure Django to upload media files to DigitalOcean Spaces when running in production. I've set up the following in my settings.py: DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('DO_SPACES_ACCESS_KEY') AWS_SECRET_ACCESS_KEY = os.environ.get('DO_SPACES_SECRET') AWS_STORAGE_BUCKET_NAME = os.environ.get('DO_SPACES_SPACE_NAME') AWS_S3_ENDPOINT_URL = os.environ.get('DO_SPACES_ENDPOINT') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_LOCATION = 'media' # Folder inside your space for uploaded files MEDIA_URL = 'https://andonov-restaurant.fra1.digitaloceanspaces.com/media/' -
ModuleNotFoundError: No module named '<appname>.wsgi'
alvin@LAPTOP-B4OCSM17 MINGW64 ~/Desktop/Work/Projects/secondChoice (main) $ gunicorn secondChoice.wsgi:application Traceback (most recent call last): File "", line 198, in _run_module_as_main File "", line 88, in run_code File "C:\Users\alvin\Desktop\Work\Projects\secondChoice\carzone\Scripts\gunicorn.exe_main.py", line 4, in from gunicorn.app.wsgiapp import run File "C:\Users\alvin\Desktop\Work\Projects\secondChoice\carzone\Lib\site-packages\gunicorn\app\wsgiapp.py", line 8, in from gunicorn.app.base import Application File "C:\Users\alvin\Desktop\Work\Projects\secondChoice\carzone\Lib\site-packages\gunicorn\app\base.py", line 10, in from gunicorn import util File "C:\Users\alvin\Desktop\Work\Projects\secondChoice\carzone\Lib\site-packages\gunicorn\util.py", line 7, in import fcntl ModuleNotFoundError: No module named 'fcntl' check your directory order it should work -
Django downloads binary file from FastAPI (MinIO presigned URL), but the file is corrupted and downloaded with wrong name
I'm using Django (frontend) and FastAPI (backend) with MinIO as file storage. My setup: FastAPI generates a presigned MinIO download_url for the file. Django fetches metadata via FastAPI, then downloads the file using requests.get(download_url, stream=True) and returns it with StreamingHttpResponse. Here is my Django view for downloading the file: from django.http import StreamingHttpResponse, Http404 from django.utils.encoding import smart_str from urllib.parse import quote import requests def download_file(request, file_id): print(f'file_id = {file_id}') try: url = f"http://89.150.34.163:8000/api/v1/student/download/{file_id}" response = requests.get(url) if response.status_code != 200: raise Http404("Файл не найден") json_data = response.json() download_url = json_data.get("download_url") original_filename = json_data.get("original_filename", f"file_{file_id}") print(f'filename: {original_filename}') if not download_url: raise Http404("Ссылка на скачивание отсутствует") file_response = requests.get(download_url, stream=True) if file_response.status_code != 200: raise Http404("Ошибка при скачивании файла") filename_ascii = smart_str(original_filename) filename_utf8 = quote(original_filename) response = StreamingHttpResponse( streaming_content=file_response.iter_content(chunk_size=8192), content_type=file_response.headers.get("Content-Type", "application/octet-stream") ) response['Content-Disposition'] = ( f'attachment; filename="{filename_ascii}"; ' f"filename*=UTF-8''{filename_utf8}" ) return response except Exception as e: print(f"Ошибка при скачивании: {e}") raise Http404("Ошибка при скачивании файла") When I download the file via browser (pasting the download_url directly), it works perfectly — correct filename and contents. But when I download it through Django the file has a corrupted name (e.g. download, загруженное, etc.). The .docx file becomes corrupted and can't be opened in … -
I changed my Django App name and not DB names do not match
I am using Django and I wanted to change an app name from "project" to "projects" to make it cleaner and match the other models. So i did the usual Django stuff. Change config name, changed config Url, change App folder name. Even changed the apps.py and the urls to app_name = 'projects' The migrations went ok. Issue is the database is still showing everything as project_*** in the database. So now I am getting errors like these: ** error relation "projects_overview" does not exist LINE 1: SELECT "projects_overview"."a_id" FROM "projects_overview" It wants the new "S". how can I get the database to show the correct prefix of projects_ and not the old project_? will I have to use Postgres commands to change all the tables manually or did I miss some Django command. DBs are not my thing so very greatful for anyones kind help. Thank you. -
python django pass css style through admin panel
I am working on project in Python Django: my_project It's like a regular blog, but you can format your content by markdown and call particular css style through admin panel like that: enter image description here Basic mardkown functions work fine, but i can't set a style like i want to in spite of that i'm using markdown.extensions: attr_list and tables: enter image description here I was trying to pass css style with various ways to django-admin panel. I expect possibility to edit post easily like in mardown with it extensions. -
Django Undo Feature - Creating a single list of actions to undo changes in multiple models
I'm starting to add an "undo" feature to a Django Web App, and I'm not sure the best approach. I looked at some of the revisioning packages like django-simple-history but ran into issues: not all of them handle bulk_update and similar methods, and since the modals are all linked and an update here triggers a bulk-update there and delete loop there, the simplest approach seems to be undo-ing one step at a time. The packages I've found want to handle each model separately without an app-wide chronological list, so to properly roll back a change I need to query every history record and sort them by date, then roll back everything until I hit the desired position. This seems to be problematic, I feel like I'll run into issues with things being out of order, or simple speed issues while pulling the last 100 records for every historical object and merging/sorting them together into a chronological list. I'm leaning towards - making an audit log of every change app-wide, marking items for deletion instead of deleting them, etc., and pretty much rolling my own system. Am I falling victim to "not invented here"? Is there a simple process I'm missing? … -
Django JSONFIeld's widget for data input in format: forms.Select (key) - forms.TextInput (value)
I have a hard times to implement "user friendly" JSON input within a form. I have some Item model which contains attributes = JSONFIeld(). class ItemType(models.Model): title = models.CharField() class Item(models.Model): title = models.CharField() item_type = models.ForeignKey(ItemType) attributes = models.JSONField() To keep particular "schema" within a single ItemType I've added models: class ItemAttribute(models.Model): title = models.CharField(max_length=100, unique=True) class ItemAttributeSpec(models.Model): item_type = models.ForeignKey(ItemType) attribute = models.ForeignKey(ItemAttribute) required = models.BooleanField(default=False) choices = models.JSONField(default=list) So a goal for implementation: Provide a set of attributes' key/value pairs where key of JSON field will be forms.Select() or just label (doesn't matter much as I can manage implementation of this feature) and value is an input. So every single Item form instance would has all type-related attributes for input. Generally some kind of formset within a single form instance. Something like this: -
unexpected keyword in createsuperuser django
I am working with BaseAbstractUser and AbstractUser, and I have a problem with a required field. models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager from django.utils.timezone import timedelta, now from django.core.exceptions import ValidationError # File validation function def validate_file_type(value): allowed_types = ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"] if value.content_type not in allowed_types: raise ValidationError("Only PDF and Word documents are allowed.") class CustomUserManager(BaseUserManager): """Manager for CustomUser""" def create_user(self, email, password=None, role="customer"): if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), role=role) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): user = self.create_user(email, password, role="admin") user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): """Custom user model using email authentication""" ROLE_CHOICES = [ ("vendor", "Vendor"), ("customer", "Customer"), ("admin", "Admin"), ] email = models.EmailField(unique=True) role = models.CharField(max_length=10, choices=ROLE_CHOICES, default="customer") is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # Required for Django admin is_superuser = models.BooleanField(default=False) # Required for superuser checks objects = CustomUserManager() # Use the custom manager USERNAME_FIELD = "email" # Set email as the primary login field REQUIRED_FIELDS = ["role"] def __str__(self): return self. Email admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model CustomUser = get_user_model() class CustomUserAdmin(UserAdmin): … -
Django ImportExport: How to remove inline <ins> tag background color in import preview with Jazzmin admin?
I'm using Django with the Jazzmin admin theme and the django-import-export package to bulk import model data through the admin panel. When importing, the import preview page highlights newly added rows or changed fields using an inline tag like this: <ins style="background:#e6ffe6;">Paris</ins> This creates an unwanted green/purple background that conflicts with my custom admin styling. **What I've tried so far:** Created custom_admin.css at: project/static/admin/css/custom_admin.css Linked it correctly in admin.py: class Media: css = { "all": ("admin/css/custom_admin.css",) } js = ("admin/js/custom_tabs.js",) Added the following aggressive CSS rule: .import-preview td ins, tr.row-new td ins, .import-preview td > ins { all: unset !important; background-color: #fff !important; color: #000 !important; display: block !important; text-decoration: none !important; width: 100% !important; } Ran collectstatic and did a full cache refresh (Ctrl+Shift+R) Verified that custom_admin.css is loaded correctly via DevTools - Still, the inline style style="background:#e6ffe6" overrides everything. What I also attempted: Overriding the template import_preview.html (placed at project/templates/import_export/import_preview.html) with a custom version that removes the <ins> tag completely and wraps cells in <div> instead. But the default template still seems to load or my override isn’t being used. My setup: Django 5.1.1. django-import-export 3.3.5. Jazzmin admin theme. Static and template settings are configured properly. Question: How … -
Rosbag and Django 5.2 with Python 3.13
I try to import the rosbag library with Django 5.2 and Python 3.13 in my docker but it doesn't work. If I try an import rosbag with a python command in the shell, it's work, but if I try the same command in the ./manage.py shell it doesn't work. I only have a gnupg INFO message likes: 2025-05-02 10:29:58,983 gnupg INFO Log opened: Fri May 2 08:29:58 2025 UTC but after nothing happens, the import is like frozen and I can't do anything. With my docker, the command works with Python3.10 but not with Python3.12 or Python3.13. In local dev with a virtual env, it's works with ./manage.py shell in both versions. If I create a new docker with python3.13.3 image, and I install all requirements from my docker and I create a new django project, the command works in the ./manage.py shell. In this new docker, I tried to copy/paste my project and it's works... I don't know where the problem might be coming from and how to track down where the import is blocking exactly... -
views have lost access to models in Django
I have DRF installed with Django, and for some reason my ModelViewSets have lost access to the models. My views.py from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import IsAdminUser from django.contrib.auth import get_user_model from rest_framework.viewsets import ModelViewSet from rest_framework.permissions import IsAuthenticated from .models import * from .serializers import * from .permissions import * # Get custom User model CustomUser = get_user_model() class VendorViewSet(ModelViewSet): queryset = Vendor.objects.all() serializer_class = VendorSerializer permission_classes = [IsAuthenticated, IsVendor] # Vendors only Settings.py does have the app listed INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #Third-Party Apps 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt.token_blacklist', 'django_filters', 'corsheaders', 'allauth', 'allauth.account', 'allauth.socialaccount', 'channels', # Required for real-time notifications 'mfa', #MFA Support # Project Apps 'VMP', #<--That is the project ] models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager from django.utils.timezone import timedelta, now from django.core.exceptions import ValidationError # File validation function def validate_file_type(value): allowed_types = ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"] if value.content_type not in allowed_types: raise ValidationError("Only PDF and Word documents are allowed.") class CustomUserManager(BaseUserManager): """Manager for CustomUser""" def create_user(self, email, password=None, role="customer"): if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), role=role) user.set_password(password) user.save(using=self._db) return user def … -
Troubleshooting 401 Unauthorized and 400 Bad Request Errors in Django and Next.js
I am making a news app using django (JWT) and nextJS(Redux, RTK query). When I try to retrieve user using useRetrieveUserQuery(), When I log into my account, I get GET http://localhost:8000/api/users/me/ 401 (Unauthorized) otherwise POST http://localhost:8000/api/jwt/refresh/ 400 (Bad Request) when coming from another user page. Here are my views - from django.conf import settings import requests from datetime import datetime, timedelta from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView ) import logging from collections import deque logger = logging.getLogger(__name__) class CustomTokenObtainPairView(TokenObtainPairView): def post(self, request, *args, **kwargs): response = super().post(request, *args, **kwargs) if response.status_code == 200: access_token = response.data.get('access') refresh_token = response.data.get('refresh') response.set_cookie( 'access', access_token, max_age=settings.AUTH_COOKIE_ACCESS_MAX_AGE, path=settings.AUTH_COOKIE_PATH, secure=settings.AUTH_COOKIE_SECURE, httponly=settings.AUTH_COOKIE_HTTP_ONLY, samesite=settings.AUTH_COOKIE_SAMESITE ) response.set_cookie( 'refresh', refresh_token, max_age=settings.AUTH_COOKIE_REFRESH_MAX_AGE, path=settings.AUTH_COOKIE_PATH, secure=settings.AUTH_COOKIE_SECURE, httponly=settings.AUTH_COOKIE_HTTP_ONLY, samesite=settings.AUTH_COOKIE_SAMESITE ) return response class CustomTokenRefreshView(TokenRefreshView): def post(self, request, *args, **kwargs): refresh_token = request.COOKIES.get('refresh') if refresh_token: request.data['refresh'] = refresh_token response = super().post(request, *args, **kwargs) if response.status_code == 200: access_token = response.data.get('access') response.set_cookie( 'access', access_token, max_age=settings.AUTH_COOKIE_ACCESS_MAX_AGE, path=settings.AUTH_COOKIE_PATH, secure=settings.AUTH_COOKIE_SECURE, httponly=settings.AUTH_COOKIE_HTTP_ONLY, samesite=settings.AUTH_COOKIE_SAMESITE ) return response class CustomTokenVerifyView(TokenVerifyView): def post(self, request, *args, **kwargs): access_token = request.COOKIES.get('access') if access_token: request.data['token'] = access_token return super().post(request, *args, **kwargs) class LogoutView(APIView): def post(self, request, *args, **kwargs): … -
single and double quotes in json.parse
How can I pass a list of characters from Django to Javascript? I'm passing a dictionary from Django to Javascript in the render function. In javascript I parse the data as always using the code const dates = JSON.parse("{{dates|safe}}") This works for numbers, but for strings I get some error JSON.parse: unexpected character at line 1 column 2 of the JSON data I could pinpoint the problem down to: const this_works = JSON.parse('["1","2"]') const this_throws = JSON.parse("['1','2']") But I can't use the ' as the outermost character here as the {{}} notation seems to require ". What is the workaround to this problem? -
Django's Password Reset Email is not rendering the CSS properly but grabbing the HTML content
I am using Django's password reset and I'm trying to send the password reset with a custom HTML template for when the user receives the email, its nicely formatted. Right now when I send it, it's sending the content of what's in the HTML file, but the styling isn't there for some reason and I can't figure out why. There should be spacing and all of that, so it looks nice, but it isn't doing it. password_reset_email.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Reset Your Password</title> <style> /* Inline styles for email clients */ body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5; margin: 0; padding: 0; } .password_reset_email { max-width: 600px; margin: 0 auto; padding: 2rem; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .password_reset_email-header { text-align: center; margin-bottom: 2rem; } .password_reset_email-header h1 { color: #2c3e50; font-size: 2rem; margin-bottom: 1rem; } .password_reset_email-content { margin-bottom: 2rem; } .password_reset_email-content p { margin-bottom: 1rem; color: #333; } .password_reset_email-button { display: inline-block; background: #3498db; color: white; padding: 0.8rem 1.5rem; border-radius: 4px; text-decoration: none; margin: 1rem 0; } .password_reset_email-footer { margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #ddd; … -
How to add a validation to a model serializer so that it ensures at least one of two fields are passed for sure?
I have made a model in Django which includes two fields, let's call them file and code. file is a file field and code is a character field. I've set them both as blank=True and null=True. Set the validation in model by overriding the clean() method to check if file and code both don't exist, it throws a validation error saying at least one should be passed. Called full_clean() in the overridden save() method. This approach does allow me to add this sort of at least one validation for these two fields on the model level and even through the admin panel. But, in the serializer, or while hitting the API, it doesn't really throw any error if I don't pass both, that's probably coz my model basically says both aren't required individually. What I tried doing is that I have overridden the validate() method in the serializer, it's a model serializer btw. In the overridden validate() method I added the check as: if file not in data and code not in data: raise serializers.ValidationError("At least one of the two must be passed.") What should I do instead? Even a change in the model might help but it should keep … -
I want to pass Hex Colour Code into a CSS inline style on an HTML page
I have a Django project that has a database of colours with their Hex values. I want to display this as a swatch in a table. <tbody> {% for item in items_page %} <tr> <td scope="row">{{ item.manufacturer }}</td> <td scope="row">{{ item.paintname }}</td> <td scope="row">{{ item.hexcode }}</td> <td scope="row">{{ item.type }}</td> <td scope="row">{{ item.colourcategory }}</td> <td scope="row" style='background-color :{{item.hexcode}}'></td> </tr> The issue I have is that this works and displays the swatches but the last line has errors flagged on it. The error red lines are under the <td tag, the word color and the {{item.hexcode}} code. It works but I worry that because of the error it may break further down the line. Is there a correct way of achieving what I am trying to do? Thanks -
Please help me understand why I shouldn't save CSRF tokens in session storage
I am new to webdevelopment and have written some tests in Playwright to test my webapplication. The tests are failing only on Webkit/safari, seemingly due to CSRF validation issues returning 403 Errors on unsafe (POST/PUT/DELETE) requests only. Backend: api.example.com (Django) Frontend: app.example.com (React.js) My current procedure: The user calls a dedicated endpoint api.example.com/api/auth/csrf/ which simply sets the csrf cookie using Set-Cookie default Django behaviour, and returns nothing in the response body. For a subsequent POST Request the csrftoken cookie is read and set as the X-CSRFToken header. The user logs in using a POST request and username password together with this header to get the sessionid in cookies. Subsequent POST requests with csrftoken and session_id in cookies fail, as my React.js application fails to create the X-CSRFToken header (empty header). This only happens for Webkit/Safari, not for Firefox or Chromium. From what I understand, is that even though the Cookies are sent across subdomains, webkit does not allow cookies to be read from document.cookies across different subdomains when setting Samesite=lax, even if the domain is set to .example.com. This is in contrast with chromium and firefox that seemingly do allow this behaviour. In all browsers, I have confirmed that the … -
How can I structure a learning platform with categorized content and searchable tutorials using Django? [closed]
I'm building a web app for educational tutorials. I want to organize content by categories like Python, SQL, and Machine Learning, and allow users to search by topic or keyword. What's a good way to design the models and implement search functionality efficiently in Django? -
How to make the logout dropdown visible in Django-Jazzmin admin panel?
"I just installed Django version 5.2 and replaced the default admin interface with Django Jazzmin version 3.0.1. However, the problem is that the logout dropdown does not appear. I’ve already asked an AI platform and tried all the suggestions provided, but none of them worked." -
Hi there, how can i get the key and values from a dictionary, so i can display each keys with their value on my Django page. I'm new to Django
I want to build a page that has each author with their quote. I have tried, but everything i tried has failed. The function below is what causes me the issues. quotes = { "Arthur Ashe": "Start where you are, Use what you have, Do what you can.", "Steve Jobs": "Don’t watch the clock; do what it does. Keep going.", "Sam Levenson": "Don’t watch the clock; do what it does. Keep going.", " Robert Collier": "Success is the sum of small efforts, repeated day in and day out.", "Nelson Mandela": "It always seems impossible until it’s done.", "Mahatma Gandhi": "The future depends on what you do today.", "Zig Ziglar": "You don’t have to be great to start, but you have to start to be great.", "Dave": "Discipline is doing what needs to be done, even if you don’t want to do it.", "Suzy Kassem": "Doubt kills more dreams than failure ever will.", "Pablo Picasso": "Action is the foundational key to all success." } def mypage(request): messages = [quotes[item] for item in quotes] authors = [item for item in quotes] return render(request, "quotes/mypage.html", {"authors": authors, "quotes":messages}) -
ensure Customuser is being used in Django App
I have a problem with implementing CustomUser in a Django App. My project is called "VendorManagement". My app is "VMP". In settings, I have AUTH_USER_MODEL = 'VMP.CustomUser' set. Here is my CustomUser Model: from django.db import models from django.conf import settings from django.contrib.auth.models import User, AbstractUser from django.utils.timezone import timedelta, now from django.core.exceptions import ValidationError # File validation function def validate_file_type(value): allowed_types = ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"] if value.content_type not in allowed_types: raise ValidationError("Only PDF and Word documents are allowed.") class CustomUser(AbstractUser): ROLE_CHOICES = [ ('vendor', 'Vendor'), ('customer', 'Customer'), ('admin', 'Admin'), ] role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='customer') groups = models.ManyToManyField("auth.Group", related_name="custom_user_groups", blank=True) user_permissions = models.ManyToManyField("auth.Permission", related_name="custom_user_permissions", blank=True) def is_vendor(self): return self.role == "vendor" def is_customer(self): return self.role == "customer" def is_admin(self): return self. Role == "admin" Here is my views: from django.contrib.auth import get_user_model from .models import * # Get custom User model CustomUser = get_user_model() class RFPViewSet(viewsets.ModelViewSet): serializer_class = RFPSerializer def get_queryset(self): """Vendors see active RFPs, Customers see expired ones""" userid = self.request.user.id # Ensure user is fetched correctly as CustomUser user_instance = CustomUser.objects.filter(id=user.id).first() if user_instance.is_vendor(): return RFP.objects.filter(is_expired=False, is_active=True) elif user_instance.is_customer(): return RFP.objects.filter(customer=user_instance, is_expired=True) return RFP.objects.none() The problme3 i that while the model does include is_customer() and is_vendor(), the functions … -
Cloud SQL Proxy SSL error: `certificate had CN "", expected "<project>:<region>:<instance>"` when connecting to PostgreSQL 14
We're encountering an issue with Cloud SQL Proxy (v1 and v2) when connecting to a newly created PostgreSQL 14 Cloud SQL instance via a Kubernetes deployment on GKE. The error we see in the logs is: certificate had CN "", expected "<project-id>:<region>:<instance-name>" Context: We're using the Cloud SQL Auth Proxy sidecar container in our GKE deployment. The credentials JSON for a service account with the Cloud SQL Client role is correctly mounted and used via -credential_file. The instance connection string is correctly formatted. We’ve verified that the secret mounts and paths are accurate. The same setup works fine for an older PostgreSQL 11 instance. Observations: Proxy starts and listens on 127.0.0.1:5432, but immediately fails on SSL handshake. The error appears to be related to the certificate’s Common Name (CN) being empty or invalid. The username used to connect differs from the old instance (proxyuser) vs. new one (postgres), but it's unclear if that's related. What we've tried: Regenerating and rotating service account keys Verifying IAM permissions Ensuring secrets are properly mounted Running the proxy locally with the same credentials (same error) Question: What could cause the Cloud SQL Auth Proxy to reject the connection due to a CN "" certificate …