Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can a Django app on a Raspberry Pi safely trigger an upgrade of itself using apt and systemd?
I'm distributing a Django/Python web application as a Debian package on a Raspberry Pi. I’d like to implement an "Upgrade" button in the web UI that triggers a sudo apt update && sudo apt -y install my_app to upgrade the application package. The challenge is that the app is trying to replace itself while it's still running — the very code initiating the upgrade is part of what will be upgraded. What I've tried: The Upgrade button sends a POST to the Django backend. The backend uses python subprocess to start a oneshot systemd unit (gui-package-update.service) that runs the upgrade commands (via sudo). The Django app itself is started on boot using another systemd service and runs as a non-root user. I've configured sudoers to allow the Django user to run sudo systemctl start gui-package-update.service without a password. A second POST api call is used to monitor the state of the upgrade, those states being: running - the server is up and running upgrading - the server has received the POST command to start an upgrade 404/500 - the server is currently rebooting The 404/500 errors are caught in the JS front end and interpreted to mean that the server … -
How to solve "X-Csrftoken HTTP header has incorrect length" error from React Native with Django API?
The program should make a POST Request to logout a React Native client (Android with Expo Go), ending it's session. The program stores both user's session id and CSRF token from Django response after login, with React Native asyncStorage. And when trying to make the logout request by sending both session id and CSRF token as headers, the program shows the title error. Logout Request const postRequestLogout = async () => { try { //getting both sessionid and csrftoken from asycStorage const sessionid_value = await AsyncStorage.getItem('sessionid') const csrftoken_value = await AsyncStorage.getItem('csrftoken') console.log("Session: ",sessionid_value) console.log("Csrf: ",csrftoken_value) //Here these values are passed to headers const requestOptions = {method:'POST',headers: {'Content-Type': 'application/json','Authorization':sessionid_value,'X-CSRFTOKEN':csrftoken_value}} await fetch( 'http://myIP/user_account/api_logout_user_account/', requestOptions) .then(response => { response.json() .then(data => { Alert.alert("Sucesss"); console.log(data) }); }) } catch(e) { console.log(e) } } Login request const PostRequestLogin = () => { const email = "myemail" const password = "mypass" setSessionId = async (value) => { try { await AsyncStorage.setItem('sessionid', JSON.stringify(value)) } catch(e) { console.log(e) } } setCsrfToken = async (value) => { try { await AsyncStorage.setItem('csrftoken', JSON.stringify(value)) } catch(e) { console.log(e) } } const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email:email,password:password}) }; const postRequestLogin = async () => … -
Verifying user location for an action in a site [closed]
I am building an Employee Management system using django and angular (that's what I am most proficient with). Now pretty much every thing is implemented except the verification for check in that proves users are actually in the office. I have two options, checking if the user is connected to the company's wi-fi(a starlink router) and checking the user's geographical location. We eliminated the option for a QR code not to need an extra device(convenience). The option of using the company network is kind of off the table because you can not get any unique information about the router from the browser(non that i know of). But for the geo location, I have used the geoip2 on django and it was not good enough. I have also used the HTML5 geolocaion from the browser but it is only accurate on mobile devices. Is there any better geoapi(preferably free. I am an just an intern), or any other way I can achieve this? I am open to any feasible ideas -
CSS Static Files Not Updating After Successful Deployment
I'm experiencing an issue with my Django application deployed on Railway where CSS changes are not being reflected on the live site, even after successful deployments and clearing browser caches. Project Setup: Framework: Django Static Files Serving: Whitenoise (whitenoise.middleware.WhiteNoiseMiddleware and whitenoise.storage.CompressedManifestStaticFilesStorage are configured) Repository Structure: Standard Django layout with manage.py, Procfile, requirements.txt in the root. settings.py/wsgi.py are in comparaplan/comparaplan/. Static source files are intended to be in comparaplan/static/. Railway Root Directory Setting: / (Repository Root) Deployment Process & What Works: Builds complete successfully. The Pre-deploy Command is set to: python manage.py migrate && python manage.py collectstatic --noinput --clear The deployment logs clearly show both migrate and collectstatic running successfully during the pre-deploy phase. collectstatic reports copying files (e.g., XXX static files copied to '/app/staticfiles'). The Start Command is set to: gunicorn comparaplan.comparaplan.wsgi --bind 0.0.0.0:$PORT --log-file - (or it's correctly defined in the Procfile and the start command field is empty). The runtime logs show Gunicorn starting successfully and listening on the correct port. The application loads without 5xx errors. The Problem: Despite the above, CSS changes made to files (specifically tested with comparaplan/static/styles/global.css) are not visible on the deployed site. Troubleshooting Steps Taken: Confirmed CSS changes were committed and pushed … -
.show() not displaying <div> on click, despite confirmed event trigger and DOM presence
My problem is the div element will not show even when using the show method and clicking on it. console.log("Profile JS loaded"); document.addEventListener('DOMContentLoaded', function () { // Find all user profile bubbles var userBubbles = document.querySelectorAll('.bubble'); userBubbles.forEach(function (bubble) { bubble.addEventListener('mouseenter', function () { var userId = bubble.getAttribute('data-userid'); var calendarEl = document.getElementById('mini-calendar-' + userId); // Fetch user events fetch(`/events/${userId}`) .then(response => response.json()) .then(events => { // Initialize FullCalendar var calendar = new FullCalendar.Calendar(calendarEl, { initialView: 'dayGridMonth', events: events, headerToolbar: false, // Hide header height: 'auto', // Adjust height contentHeight: 'auto', // Adjust content height editable: false, // Disable editing selectable: false // Disable selection }); calendar.render(); }) .catch(error => console.error('Error fetching events:', error)); // Show the mini calendar popup calendarEl.classList.add('show'); }); bubble.addEventListener('mouseleave', function () { var userId = bubble.getAttribute('data-userid'); var calendarEl = document.getElementById('mini-calendar-' + userId); // Hide the mini calendar popup calendarEl.classList.remove('show'); }); var profilejson = $("#profile-safe").text(); console.log('PROFILESAFE: ' + profilejson); const profiles = JSON.parse($("#profile-safe").text()); console.log(profiles); const heartbeatInterval2 = 1000; async function updateStatus() { for (let i = 0; i < profiles.length; i++) { const userId = profiles[i].user.id; try { const response = await $.ajax({ url: '/status/' + userId, method: 'GET', }); if (response == true) { document.getElementById('user-dot-' + userId).style.backgroundColor = … -
Django Autocomplete reversed ForeignKey field
I have two models models.py class Group(models.Model): name = models.CharField() class Book(models.Model): name = models.CharField() group = models.ForeignKey(Group, on_delete=models.SET_NULL, related_name='books', related_query_name="book", null=True, blank=True) I need in admin panel add to Group form multiple select for books. I have successfully solved this problem using the code below. admin.py from .models import Group, Book from django.forms import ModelForm, ModelMultipleChoiceField from django.contrib.admin import widgets class Group_ModelForm(ModelForm): books = ModelMultipleChoiceField(queryset=Book.objects.all(), widget=widgets.FilteredSelectMultiple('Books', False), required=True, label='Books') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'instance' in kwargs and kwargs['instance'] is not None: self.fields['books'].initial = kwargs['books'].books.all() @admin.register(Group) class Group_ModelAdmin(admin.ModelAdmin): list_display = ['name'] list_display_links = ['name'] fields = ['books', 'name'] form = Group_ModelForm def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if change: Book.objects.filter(group=obj).update(group=None) form.cleaned_data['books'].update(group=obj) But, when the number of books exceeded 100 000, the Group form took a long time to load, because FilteredSelectMultiple load all 100 000 objects on init. I try replace FilteredSelectMultiple widget to AutocompleteSelectMultiple widget, but AutocompleteSelectMultiple do not work without many-to-many field in Group model. I try override AutocompleteMixin class to create custom AutocompleteSelectMultiple widget, but I didn’t succeed: the AutocompleteSelectMultiple widget still required a many-to-many field in Group model. How to do autocomplete select widget for custom field books in … -
Django ORM: Error when assigning foreign key instance from CSV import
I have module that responsible for update insurance data the module job : takes data from csv takes the values and validate it and then update for empty columns within the sheet it will keeps the old data as it's it contains 2 foreign keys from different tables at Box Number and Policy Id it works with transaction.atomic() (it will update the data and stops when found error within specific row) import csv from datetime import datetime from django.db import transaction from arcapp.models import Box, ProviderSegregation, insurance_policy def process_provider_segregation_csv(csv_file, request): """ Process a CSV file to update ProviderSegregation records. Handles both regular fields and foreign key fields properly. """ updated_count = 0 errors = [] try: decoded_file = csv_file.read().decode("utf-8").splitlines() csv_data = csv.DictReader(decoded_file) # Check required columns headers = csv_data.fieldnames if 'ClaimCode' not in headers: return 0, ["CSV file must contain a 'ClaimCode' column"] # Process in a transaction to ensure data consistency with transaction.atomic(): for row_num, row in enumerate(csv_data, start=2): # Start from 2 for header offset try: # Get ClaimCode which is required for lookup claim_code = row.get('ClaimCode', '').strip() if not claim_code: errors.append(f"Row {row_num}: Missing ClaimCode") continue # Find the record by ClaimCode try: record = ProviderSegregation.objects.get(ClaimCode=claim_code) except ProviderSegregation.DoesNotExist: … -
New media files not found at django website hosted on azure
A Django website works correctly both locally and on PROD. PROD is azure app service. Since it's deployed to a temporary storage (container, I presume), which is overriden with each deploy, I don't want media files to be overriden every time. So I've moved them to the media folder outside of deployed website folder, but it's inside site/wwwroot, so that I can use it via ftp as well. And those files that where already in the folder site/wwwroot/media, are working fine. But new ones return 404 error on attempt to read them. I've checked and those new files exist and they are exactly in the same folder as old images. I've double checked and tried the same url from the old image, copy-pasted new image file name from ftp on PROD and pasted it into the browser, but it still gives me 404 error. So for some weird reason website can access file system to read and write, but on attempt to open in browser any image file that was uploded after deploy, it fails. It feels like it's just remembering a list of files there and doesn't even check if actual file exists if it wasn't there on deploy. … -
Authenticating to a django backend from a vite frontend on a different subdomain hosted on self-hosted coolify instance
Hello I am trying to deploy two applications to a self hosted Coolify instance and I am unable to authenticate from my frontend. They are on different subdomains as you can see from the example below: Vite frontend (format): https://project.mydomain.com/#/login Django backend (format): https://api.mydomain.mydomain.com/ (Also one thing to mention is that I am using caddy as my reverse proxy in Coolify) When I try to login from the frontend I get the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.mydomain.mydomain.com/api/api-token-auth/. (Reason: header ‘access-control-allow-origin’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response) I have been reading about CORS for days and still cannot figure it out. I have configured my django backend with the following settings installed django-cors-headers made these changes to my settings.py INSTALLED_APPS = [ # in project 'budget', # installed Packages 'rest_framework', 'rest_framework.authtoken', "crispy_forms", "crispy_bootstrap5", "corsheaders", # # --------------- 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) CORS_ALLOWED_ORIGINS = [ 'https://project.mydomain.com', ] # CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', … -
Djoser | password reset nightmare
I’m using Djoser + Django REST Framework for authentication and I’m getting a little frustrated about the password‑reset flow (JUST A LITTLE 🥲). My password‑reset emails generates links like: (http://localhost:8000/auth/users/reset_password_confirm/uid/token/) The problem is that this endpoint expects a POST with the user’s new password, but clicking the link issues a GET, so the request fails immediately. Most of the solutions I’ve found feel hacky, because they require either: Overriding the Djoser view to handle a GET (redirecting to my frontend) and then handling a POST to the same URL to set the new password Modifying Djoser’s email templates (which just feels bad to me) Does anyone know a cleaner way to work around this? Any alternative patterns, suggestions, or insights would be hugely appreciated! -
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): …