Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe 404 with DJStripe and Django
I am running a django app using stripe for payments. Upon running stripe cli I am encountering 404 errors when triggering payment events. project level urls.py path('api/payments/', include('payments_app.urls')) payments_app level urls.py: path('stripe/', include('djstripe.urls', namespace='djstripe')) I am consistently encountering the following errors: 2025-01-19 22:04:48 --> customer.created [evt_1QjCEGKCdat1JCnURBfuIFLH] 2025-01-19 22:04:48 <-- [404] POST http://localhost:8000/api/payments/djstripe/ [evt_1QjCEGKCdat1JCnURBfuIFLH] I can assure you that the API keys have been set correctly as I was able to successfully sync from the products and prices. I ran many permutations of the following url with changing the urlpatterns stripe listen --forward-to http://localhost:8000/api/payments/stripe/webhook I tried running: curl -X POST http://localhost:8000/payments/stripe/webhook -H "Content-Type: application/json" -d '{}' It also give a 404 -
Django refuses connection on AWS instance
I have a django app which is close to the default install app. In settings.py I have DEBUG = False ALLOWED_HOSTS = ['*'] I have added a url server/get_something which I can request and returns fine when I am running the server locally using python manage.py runserver I have installed and run my app on an AWS instance using port 7500, and I have opened that port to all addresses in the AWS security group like this: However when I make my request from a remote computer (to the AWS instance) I get a "refused to connect" error. There is no relevant printed output on the django process. It is worth noting that if I try to connect to a different port, it times out, so I think that the request is getting past AWS' firewall. But I can't work out why it isn't getting to django on the instance. Also, I have used curl locally on the AWS instance: curl 127.0.0.1:7500/server/get_something And this works fine. -
ModuleNotFoundError: No module named 'wagtail.contrib.modeladmin' when i try to write "wagtail.contrib.modeladmin' on base.py file it rise this error
from django.contrib import admin from .models import Subscribers @admin.register(Subscribers) class SubscriberAdmin(admin.ModelAdmin): """Admin configuration for Subscribers.""" model = Subscribers menu_label = "Subscribers" menu_icon = "placeholder" menu_order = 290 add_to_settings_menu = False exclude_from_explorer = False list_display = ("email", "full_name",) search_fields = ("email", "full_name",) this was my admin.py file -
Django 5.0.x async with raw query set & iterator
I have a raw query set that returns a few millions of elements. Actually, I use the iterator() function of django to improve performances. The problem I have here, is that I want to make the function where the query is called asynchronous. Because of that, I can't make Django raw queryset anymore because I get this error : django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Using sync_to_async makes the use of iterator impossible. There is the aiterator() function, but it doesn't work on raw query set.. How can I use iterator with a raw query set in an asynchronous context ? Code : def _get_elements_to_process(self): return Elements.objects.raw( """ My query """, ) async def fetch_data(self): for element in _get_elements_to_process().iterator(): # make some asynchronous action -
I can't create a new url on django
i've watched some tutorials on how to create a new simple url and for some reason it doesn't work, it looks like i didnt registred any urls even though i did. i created an app called 'Login' and registered it in the "INSTALLED APPS" list on settings.py of django : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Login.apps.LoginConfig', ] then i created the function called 'home' on the views file of the app, to show a phrase on the page: from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('Hello') and then i created a new url path on the urls.py file of the project, without a name at first, just (""): from django.contrib import admin from django.urls import path from Login.views import home urlpatterns = [ path('admin/', admin.site.urls), path('', views.home), ] and when i use the (python manage.py runserver) command it just got back to the "success install" page of django, the one with the little rocket. Then I tried using a name for the url ("home/"): from django.contrib import admin from django.urls import path from Login import views urlpatterns = [ path('admin/', admin.site.urls), path('home/', views.home) ] but when i access the (localhost:8000/home/) it says … -
python package `drf-comments` not being recognized
i am developing a rest-based django project. i want to implement a commenting system in my project; but it has to be decoupled from the other apps. therefore, deepseek suggested to use drf-comments in my project. the whole thing seems appealing; as it does not require writing any model, view, serializer and url. deepseek just told me to add the urls coming from the drf-comments package and i did so. everything looks fine; but when i attempt to run the command python manage.py makemigrations or the migrate command, i get the error: ModuleNotFoundError: No module named 'drf_comments' and i got back to my chatbots (deepseek and blackbox) and they told me to go back, delete-recreate the venv to make sure everything works fine; but i know it is fine. does anybody know what's the problem with this python package (drf-comments)? maybe it is not supported anymore. additional information: python version: Python 3.11.4 the pip list: asgiref 3.8.1 certifi 2024.12.14 cffi 1.17.1 charset-normalizer 3.4.1 defusedxml 0.8.0rc2 Django 5.1.4 djangorestframework 3.15.2 djangorestframework_simplejwt 5.4.0 djoser 2.3.1 drf-comments 1.2.1 drf-nested-routers 0.94.1 idna 3.10 oauthlib 3.2.2 pip 24.3.1 pycparser 2.22 PyJWT 2.10.1 python3-openid 3.2.0 requests 2.32.3 requests-oauthlib 2.0.0 setuptools 65.5.0 social-auth-app-django 5.4.2 social-auth-core 4.5.4 sqlparse … -
What component might emit 'Request max total header size exceeded'
I am posting documents into paperless-ngx via REST api. For some pdf documents the API reliably responds with {"detail":"Multipart form parse error - Request max total header size exceeded."} I checked one of the offending documents and found it to be a normal, valid PDF of about 180 kb size. There should not be too much fuss about it, yet I have that error. Now I am wondering where this error might come from and how to get around it. Does it come from GUnicorn, Django or maybe the application itself? -
I can't use UUID with DJ-STRIPE: DJStripe: Account has no field named 'uuid'
I am attempting to setup djstripe bit am encountering the following error. settings.py: DJSTRIPE_SUBSCRIBER_MODEL = 'auth_app.CustomUser DJSTRIPE_FOREIGN_KEY_TO_FIELD = 'uuid' AUTH_USER_MODEL = 'auth_app.CustomUser' This is my models.py. Note that I am using abstractcuser in order to use email as the username. from django.db import models from django.contrib.auth.models import AbstractUser import uuid from cuser.models import AbstractCUser class CustomUser(AbstractCUser): uuid = models.UUIDField(default=uuid.uuid4, unique=True) email = models.EmailField(unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email This is the error that I am facing: raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: Account has no field named 'uuid' I have tried to delete the migrations folder and the database file but the issue persists. Please let me know if you require any further information. Thank you. -
Django relation on two database columns
I am using django to interface with an existing database that I have no control over. The database frequently uses multiple columns for making relations and has uniqueness over all of those columns. The django inspectdb model generator correctly identified these as unique_together = (('foo', 'bar'), ('foo', 'bar'),), resulting in the following model: class A(models.Model): foo = models.IntegerField(db_column='FOO', primary_key=True) bar = models.IntegerField(db_column='BAR') class Meta: managed = False db_table = 'A' unique_together = (('foo', 'bar'), ('foo', 'bar'),) Now there is another table whose entries relate to that table on both columns. When querying using SQL I would relate them like this: SELECT * FROM A LEFT JOIN B ON A.foo = B.foo AND A.bar = B.bar However inspectdb failed to correctly map the two columns being used in a relating table: class B(models.Model): foo = models.OneToOneField(A, models.DO_NOTHING, db_column='A', primary_key=True) bar = models.ForeignKey(A, models.DO_NOTHING, db_column='A') The above is what it generated, however in reality it is a many-to-one relationship to table A. This then causes an error at runtime because the column bar in table A is not unique. Can I somehow define this relationship in a django model? And how do I query this efficiently so that django generates a JOIN … -
m2m_changed instance when in reverse
I have the following signal: @receiver(m2m_changed, sender=User.cars.through): def car_added_to_user(sender, instance, action, *kwargs): if action in ("post_add",): cache.delete(f"user-{instance.pk}") I can trigger it as expected when doing: User.cars.add(car) but if I also want to delete the user from the cache in this case, what do I do? Car.user_set.add(user) as in this case the instance is a Car object and not a User object. -
why "django-admin --version" command doesn't give any output?
I had install django successfully and I change script path also but still I didn't receive any answer for (django-admin --version) command i type django-admin --version I need the installed version as the output.But I didn't receive anything. -
django-tenant-schema migration issue: IntegrityError: insert or update on table "auth_permission" violates foreign key constraint
requirements.txt: Django==4.2.16 django-tenant-schemas==1.12.0` django-allauth==65.0.2 Added a new django model, then ran migrations: ./manage.py migrate_schemas --schema=public ./manage.py migrate_schemas --schema=myschema The first command runs fine. The second command gives this error: django.db.utils.IntegrityError: insert or update on table "auth_permission" violates foreign key constraint "auth_permission_content_type_id_2f476e4b_fk_django_co" DETAIL: Key (content_type_id)=(115) is not present in table "django_content_type". Indeed, the auth_permission table does not (yet) contain any permissions related to the new model. But actually, value '115' is present in the public.django_content_type table, with the right app_label and model info. So unclear why this error is raised. Maybe the migration is not looking in the public schema? But other migrations have been running for ages, only the new table creation seems to cause a problem now. -
How to get ckeditor5 link settings to work with Django project
I installed django-ckeditor-5 and I am using it as the editor for a django-machina forum. The editor displays on the forum and basically works correctly. However, I want links to open in a new tab when clicked and I want "https://" to be automatically inserted if the user does not add it to their link when using the link button. I can not get the link attributes to work. Here are my machina settings: MACHINA_MARKUP_LANGUAGE = None MACHINA_MARKUP_WIDGET = 'django_ckeditor_5.widgets.CKEditor5Widget' Here are my ckeditor config settings: CKEDITOR_5_CONFIGS = { 'default': { 'toolbar': ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ], }, 'link': { 'addTargetBlank': True, # Open links in a new tab 'defaultProtocol': 'https', # Default protocol for links is https 'plugins': ['AutoLink'], }, 'extends': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', 'bulletedList', 'numberedList', '|', 'blockQuote', ], 'toolbar': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough', 'code','subscript', 'superscript', 'highlight', '|', 'codeBlock', 'sourceEditing', 'insertImage', 'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'imageUpload', '|', 'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', 'insertTable',], 'image': { 'toolbar': ['imageTextAlternative', '|', 'imageStyle:alignLeft', 'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side', '|'], 'styles': [ 'full', 'side', 'alignLeft', 'alignRight', 'alignCenter', ] }, # 'table': { # 'contentToolbar': [ 'tableColumn', 'tableRow', 'mergeTableCells', … -
i have a problem with the importation of wagtail.contrib.settings.models import ModelSettings
from django.db import models from wagtail.admin.panels import FieldPanel, MultiFieldPanel from wagtail.contrib.settings.models import ModelSettings,register_setting @register_setting class SocialMediaSettings(ModelSettings): """Social media settings for our custom website.""" facebook = models.URLField(blank=True, null=True, help_text="Facebook URL") twitter = models.URLField(blank=True, null=True, help_text="Twitter URL") youtube = models.URLField(blank=True, null=True, help_text="YouTube Channel URL") panels = [ MultiFieldPanel([ FieldPanel("facebook"), FieldPanel("twitter"), FieldPanel("youtube"), ], heading="Social Media Settings") ] i have already upgrade to the latest version of wagtail but still rise the ImportError: cannot import name 'ModelSettings' from 'wagtail.contrib.settings.models -
simplejwt & allauth - auth cookie not sent from browser to django backend
I have a Django backend that uses allauth and simplejwt (both provided by dj-rest-auth) for authentication. When I make API requests using an API client (Bruno), my auth cookies containing JWT tokens are passed, and the server responds. But, I can't achieve the same thing in JS from the browser. The authentication cookies are received, but not passed in subsequent requests: minimal front-end JS: (async () => { console.log("logging in...") const loginResponse = await fetch('http://127.0.0.1:8000/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'test', password: 'securepassword123' }) }) const loginData = await loginResponse.json(); // response contains `set-cookie` headers // vv prints JSON containing "access", "refresh", "username", etc. console.log(loginData) if (!loginResponse.ok) { console.log('login failed :(') return } console.log("getting user info...") const userResponse = await fetch('http://127.0.0.1:8000/api/user', { credentials: 'include' }); const userData = await userResponse.json(); // vv prints `{detail: 'Authentication credentials were not provided.'}` console.log(userData) if (!userResponse.ok) { console.log("user data fetch failed :(") } })(); I've already set up CORS, allow-credentials, etc. in Django: # dj-rest-auth settings --------------------------------- # src: https://medium.com/@michal.drozdze/django-rest-apis-with-jwt-authentication-using-dj-rest-auth-781a536dfb49 SITE_ID = 1 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ) } # djangorestframework-simplejwt SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(hours=1), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } # dj-rest-auth REST_AUTH = … -
django-allauth with steam
as describe in this [issue on github][https://github.com/pennersr/django-allauth/issues/3516], my login method which is working by the way, seems to throw an exception everytime it is used: Missing required parameter in response from https://steamcommunity.com/openid/login: ('http://specs.openid.net/auth/2.0', 'assoc_type') Traceback (most recent call last): File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/message.py", line 481, in getArg return self.args[args_key] ~~~~~~~~~^^^^^^^^^^ KeyError: ('http://specs.openid.net/auth/2.0', 'assoc_type') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/consumer/consumer.py", line 1286, in _requestAssociation assoc = self._extractAssociation(response, assoc_session) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/consumer/consumer.py", line 1402, in _extractAssociation assoc_type = assoc_response.getArg(OPENID_NS, 'assoc_type', no_default) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/message.py", line 484, in getArg raise KeyError((namespace, key)) KeyError: ('http://specs.openid.net/auth/2.0', 'assoc_type') assoc_type is misssing from steam respone. These are my app settings: INSTALLED_APPS = [ ... # social providers "allauth.socialaccount.providers.openid", "allauth.socialaccount.providers.steam", ... ] MIDDLEWARE = [ ... "allauth.account.middleware.AccountMiddleware", # social providers ... ] AUTHENTICATION_BACKENDS = ( "allauth.account.auth_backends.AuthenticationBackend", "django.contrib.auth.backends.ModelBackend", ) SOCIALACCOUNT_PROVIDERS = { "steam": { "APP": { "client_id": STEAM_SECRET_KEY, "secret": STEAM_SECRET_KEY, } }, } Did I miss something in my implementation ? Is there a way to avoid the raising of this exception ? -
dj-rest-auth access token not sent from react font-end to django back-end
I'm making an SPA with a React front-end and a Django back-end. For user authentication, I'm using dj_rest_auth, which wraps allauth to provide a REST API interface. dj-rest-auth provides a "login" endpoint that sends back access and refresh cookies. It also privides a "user" endpoint that returns the username, email, first name and last name. Both work as expected in my API client (Bruno), BUT, I can't get the "user" api to work in my front-end code. My browser doesn't send cookies to the server. Here are screenshots from Bruno. Notice how the cookies are saved, and fetching the user's info works: Here's my login request from my React app and the set-cookie headers (aka response cookies): // ... fetch(BACKEND_URL + "/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username: username, password: password, }), }) .then(async (response) => { //... study_stream_auth_cookie=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzM3MjM3MTEyLCJpYXQiOjE3MzcyMzM1MTIsImp0aSI6IjNjZDc4ZjI3ZWYyNTQwMzI4MmVmNjAwODRiMjcxYzU0IiwidXNlcl9pZCI6NDB9.JK-SKSGMWuTBFm4JFk4-T8RqNEf2vwANrS4-h7P9UMY; expires=Sat, 18 Jan 2025 21:51:52 GMT; Max-Age=3600; Path=/; SameSite=Lax study_stream_refresh_cookie=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTc0NTAwOTUxMiwiaWF0IjoxNzM3MjMzNTEyLCJqdGkiOiJhMTljYjg1ZDI5Zjk0NTQyOWUzMjM2ODdmY2IxYzQ0YiIsInVzZXJfaWQiOjQwfQ.xvfB61xkq9NUzQSZeAJmXSYaFrYcSfrsJ9QX2u635LU; expires=Fri, 18 Apr 2025 20:51:52 GMT; Max-Age=7776000; Path=/; SameSite=Lax sessionid=qt2yxaiitghqavr74xvvl8icjlckq6by; expires=Sat, 01 Feb 2025 20:51:52 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure And here's my "user" GET request. Notice that the only cookie sent here is csrftoken which is unrelated. const response = await fetch(BACKEND_URL + "/api/auth/user/", … -
Django AWS S3 JSPDF not loading image cors
I would appreciate some help. On my development I am able to create a PDF with an image without any problems, when i try the same page on my production I keep getting and error on my console and it gives me a pdf without the image. Access to image at 'https://example.s3.amazonaws.com/static/logos/example.png' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Error loading image https://example.s3.amazonaws.com/static/logos/example.png AWS settings: Block all public access: Off bucket policy: { "Version": "2012-10-17", "Id": "Policy1735675563626", "Statement": [ { "Sid": "Stmt1735675561227", "Effect": "Allow", "Principal": "*", "Action": [ "s3:DeleteObject", "s3:GetObject", "s3:GetObjectAcl", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": "arn:aws:s3:::cabiunascompras/*" } ] } I have this as my CORS policy on AWS bucket [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] And this is my javascript to build pdf: function printOC() { $('#print-oc').show() const { jsPDF } = window.jspdf; const input = document.getElementById('print-oc'); const pdf = new jsPDF({ orientation: 'portrait', unit: 'pt', format: 'a4', compress: true, }); pdf .html(input, { margin: [10, 0, 10, 0], autoPaging: 'text', html2canvas: { scale: 595.26 / srcwidth, //595.26 is the width of A4 page … -
Office 365 (exchange) modifies email headers
In my application's backend (Django) I send emails to contacts. I sometimes expect contacts to reply those emails (helpdesk application). Using classic SMTP/IMAP-POP email server (hosted on OVH) everything works fine. I use References and Message-ID headers when sending emails, and use In-Reply-To as well as References to identify inbound messages and find the source ticket (I keep message-id on ticket and related messages). But when I added O365 Exchange support, whereas it's still able to send and read emails, everytime it was creating a new ticket instead of a new message in an existing ticket. I spent time troubleshooting the issue and found out that my custom References and Message-ID were renamed by respectively x-references and x-message-id, and their value was replaced by Microsoft ones. So of course, when replying I wasn't able to find back the values I expected. And furthermore, those x-references and x-message-id were not coming back with the reply. Whereas I found a trick to make it work again, with some extra code (I use an alias in Reply-To e.g.: support+ticket-12345@mydomain.com which enables me to find the ticket back), it is ugly and people might be tempted to use another idea and make a mess, … -
static assets not found in Django web application
I am new to Django. This is my first attempt to set up a project in Django. I have run this application before and all my static files were displaying as expected. But after some time and restarting my machine, the static files are no longer displaying. Here is the project structure And this is the error messages I get My settings.py is as follows: """ Django settings for DebbyrichCollections project. Generated by 'django-admin startproject' using Django 5.1.3. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ from pathlib import Path from django.conf.urls.static import static import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-%0!($(z=yfs)tik4630krj64)m+h7o12@bujz)v+lh5j+3z%7=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] 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 = 'DebbyrichCollections.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': … -
DjangoCodeError in Download?
Traceback (most recent call last): File "/Users/yavuzhanis/opt/anaconda3/lib/python3.9/wsgiref/handlers.py", line 138, in run self.finish_response() File "/Users/yavuzhanis/Desktop/fettucini/restaurant_management/venv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 173, in finish_response super().finish_response() File "/Users/yavuzhanis/opt/anaconda3/lib/python3.9/wsgiref/handlers.py", line 183, in finish_response for data in self.result: File "/Users/yavuzhanis/opt/anaconda3/lib/python3.9/wsgiref/util.py", line 37, in next data = self.filelike.read(self.blksize) ValueError: read of closed file How can I solve the error I encountered when trying to download the end of day report I created? -
ImportError: cannot import name 'Tensor' from 'torch' (unknown location)
I’m trying to import Tensor from PyTorch, but I keep getting this error: ImportError: cannot import name 'Tensor' from 'torch' (unknown location) Here’s the code causing the issue: from torch import Tensor What I’ve Tried: Checked that PyTorch is installed (pip show torch), and I’m using version 2.5.1. Reinstalled PyTorch: pip uninstall torch pip install torch Tested the import in a Python shell, but the error persists. Environment: Python version: 3.10 PyTorch version: 2.5.1 OS: Windows 10 Virtual environment: Yes How can I fix this issue? -
Can not load static files after wapping content with django, datatable and htmx
I have a django problem where I use Datatable to display my tables I also use htmx for CRUD but the concern is that once rendered the table content, DataTable and other JS or css frameworks do not initialize after the Swap. How can I solve this problem? I collect static with django commande Python manage.py collectstatic -
SMTP Error (gmail sending) Using Django with Railway in Deployment
I am getting the following error in Railway Deploy logs when it is trying to send Gmail. Internal Server Error: /register/ Traceback (most recent call last): File "/opt/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/opt/venv/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/opt/venv/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/hostel_app/views.py", line 43, in post CustomUserSerializer().send_verification_email(user, token) File "/app/hostel_app/serializers.py", line 56, in send_verification_email send_mail(subject, message, email_from, recipient_list) File "/opt/venv/lib/python3.11/site-packages/django/core/mail/__init__.py", line 88, in send_mail return mail.send() ^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/core/mail/message.py", line 301, in send return self.get_connection(fail_silently).send_messages([self]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/core/mail/backends/smtp.py", line 128, in send_messages new_conn_created = self.open() ^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/core/mail/backends/smtp.py", line 95, in open self.connection.login(self.username, self.password) File "/root/.nix-profile/lib/python3.11/smtplib.py", line 750, in login raise last_exception File "/root/.nix-profile/lib/python3.11/smtplib.py", line 739, in login (code, resp) = self.auth( ^^^^^^^^^^ File "/root/.nix-profile/lib/python3.11/smtplib.py", line 662, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. For more information, … -
How to delete cookie with Django in Docker?
I'm working on my Django website, and I can't delete the JWT auth cookie upon logout. Here's my code for the logout view: `@api_view(['GET']) def LogoutUser(request): response = Response("logging out", status=status.HTTP_200_OK) response.delete_cookie("jwt_token", path="/") return response` It's supposed to delete the jwt_token cookie, which is the JWT auth cookie with the JWT, but for some reason it only works in my development environment (runsever), but not when it's running inside a Docker container. I tried setting a cookie with the same name but changing the expiry to 0, but that doesn't work.