Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mixin for making third-party Django model fields typed
Given the problem that not all libraries add type annotations, I am trying to build a mixin that would allow me to add type hints easily. Without that, the type-checker infers the type of the model instance field as that of the underlying built-in field’s value (e.g., str, int, date, etc.) that the custom field is built upon (or Unknown). Here is an example: from django.db import models # ========== defined in a third-party library ========== class StructuredCountry: iso_code: str ... class CountryField(models.CharField): # Not shown: the textual value from the database # is converted to a StructuredCountry object. pass # ========== defined in my own code ==================== class MyModel(models.Model): country = CountryField() reveal_type(MyModel().country) # ⇒ str MyModel().country.iso_code # E: Attribute "iso_code" is unknown For the above example, I would like to be able to: class TypedCountryField(FieldAnnotationMixin, CountryField): pass class MyModel(models.Model): country = TypedCountryField() reveal_type(MyModel().country) # ⇒ StructuredCountry MyModel().country.iso_code # ✔ So far I have come up with the following (inspired by VSCode’s stubs), which indeed works. if TYPE_CHECKING: class FieldAnnotationMixin[FieldClassType: type[models.Field], ValueType]: def __new__(cls, *args, **kwargs) -> FieldClassType: ... # Class access @overload def __get__(self, instance: None, owner: Any) -> Self: ... # type: ignore[overload] # Model instance access … -
pythonanywhere - ModuleNotFoundError: No module named 'posthog'
I'm uploading my django web app project to pythonanywhere and I'm getting this error : ModuleNotFoundError: No module named 'posthog' I tried following the pythonanywhere.com page that talks about debugging import error issues but I'm confused on how to go about it wsgi: import os import sys path = '/home/Shalz/UniHustle_back_iv' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'unihustle.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() in my settings.py file, I have import posthog posthog does not appear in my requirements.txt file though, despite installing it via my project terminal. -
ORA-00001: unique constraint (SDESERP.UK_CODELKUP) violated, django inlineformset
Hi I am trying to create a form with parent-child models using python Django Inlineformset_factory but when I am trying to update the child, its giving me unique constraint error. Here I am sharing my model code, forms code, views code. I am trying to solve this issue since last two days but not succeeded. please help me to solve the issue. Models code--> class CodeList(models.Model): listname = models.CharField(db_column='LISTNAME', max_length=20, primary_key=True) description = models.CharField(db_column='DESCRIPTION', max_length=100) adddate = models.DateField(db_column='ADDDATE') addwho = models.CharField(db_column='ADDWHO', max_length=20) editdate = models.DateField(db_column='EDITDATE') editwho = models.CharField(db_column='EDITWHO', max_length=20) class Meta: db_table ='CODELIST' def __str__(self): return f"{self.listname}" class CodeLkup(models.Model): listname = models.ForeignKey(CodeList, db_column='LISTNAME', on_delete=models.CASCADE) code = models.CharField(db_column='CODE', max_length=30, primary_key=True) #, eng_desc = models.CharField(db_column='ENG_DESC', max_length=250) bl_desc = models.CharField(db_column='BL_DESC', max_length=250, blank=True) adddate = models.DateField(db_column='ADDDATE') addwho = models.CharField(db_column='ADDWHO', max_length=20) editdate = models.DateField(db_column='EDITDATE') editwho = models.CharField(db_column='EDITWHO', max_length=20) class Meta: db_table = 'CODELKUP' unique_together = ('listname', 'code') def __str__(self): return f"{self.code}-{self.eng_desc}"``` forms code--> class CodeListForm(forms.ModelForm): class Meta: model = CodeList fields = ['listname','description'] widgets ={ 'listname' : forms.TextInput(attrs={'class' : 'form-control form-control-sm', 'autocomplete' : 'off'}), 'description' : forms.TextInput(attrs= {'class' : 'form-control form-control-sm' , 'autocomplete' : 'off'}) } def __init__(self, *args, **kwargs): is_edit = kwargs.pop('is_edit', False) self.request = kwargs.pop('request', None) super(CodeListForm, self).__init__(*args, **kwargs) if is_edit: self.fields['listname'].widget.attrs['readonly']=True def … -
Im trying to create an order for my application i have a big issue with the webhook
@login_required def cart_detail(request): # Try to fetch the cart for the logged-in user cart = Cart.objects.filter(user=request.user).first() if not cart or not cart.items.exists(): # Ensure that cart has items # If no cart exists or cart is empty, pass a flag to indicate an empty cart context = {'cart_exists': False} return render(request, 'services/cart_detail.html', context) # Calculate the total price for the cart total_price = sum(item.total_price() for item in cart.items.all()) context = { 'cart': cart, 'total_price': total_price, 'cart_exists': True, 'STRIPE_PUBLISHABLE_KEY': settings.STRIPE_PUBLISHABLE_KEY, } return render(request, 'services/cart_detail.html', context) Payment is initiated with the cart detail goes to create checkout class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): cart = get_object_or_404(Cart, user=request.user) if not cart.items.exists(): return JsonResponse({'error': 'Cart is empty'}, status=400) line_items = [] total_price = 0 # To calculate total price of the cart for the order # Prepare line items for Stripe for item in cart.items.all(): name = item.plan.name if item.plan else item.extra_service.title amount = int(item.get_price() * 100) # Amount in cents for Stripe total_price += item.total_price() line_items.append({ 'price_data': { 'currency': 'usd', 'unit_amount': amount, 'product_data': { 'name': name, }, }, 'quantity': item.quantity, }) success_url = request.build_absolute_uri('/success/') cancel_url = request.build_absolute_uri('/cancel/') # Create Stripe Checkout session checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=line_items, mode='payment', success_url=success_url, cancel_url=cancel_url, ) # … -
Using Password Recovery system in django.contrib.auth through email
In my Django project I am trying to use user password management as provided in django.contrib.auth. My set up works as expected (and as explained in Django docs) except: password recovery through Email, when the sites options (django.contrib.sites and SITE_ID) are added in settings.py. Before adding the sites options, the password recovery "link" (received in terminal console) would be something like: http://127.0.0.1:8000/reset/MQ/xxx123-11111a0c4a6czz43b314b089a544v666hhh2/ In the this instance (sites options are not added), using the link brings up the Password reset page as expected. However, after the sites options are added, the link received changes to be: http://example.com/reset/MQ/xxx123-11111a0c4a6czz43b314b089a544v666hhh2/ In the 2nd instance (i.e. received link starting with domain example.com), the password reset page does not show up (browser issues a message: No internet). If sites domain and name field values are changed (in Admin) and changed to say, xyz.com; the link received changes to: http://<domain>/reset/MQ/xxx123-11111a0c4a6czz43b314b089a544v666hhh2/ and in this case also, the Password reset page fails to show up (with a message like): `This site can’t be reached` As the process for implementing password recovery is well documented, I am not adding them here. My question is: Why does the recovery system fails when sites options are added to settings.py? Is it possible … -
having an error while hosting a django website on a heroic suggest me some good platform [closed]
I have made a website using django and purchased a domain on go daddy but could not find any platform to host. found one heroic but having some error into vs code while trying to install heroku. Any idea where can I host it ?? suggest me guys -
Django ValueError: Cannot query "instructor": Must be "User" instance
I'm getting the following error when trying to access my homepage: ValueError at / Cannot query "instructor": Must be "User" instance. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 5.2 Exception Type: ValueError Exception Value: Cannot query "instructor": Must be "User" instance. Exception Location: C:\Users\User LENOVO\OneDrive\Bureau\E-Learning\venv\Lib\site- packages\django\db\models\sql\query.py, line 1346, in check_query_object_type Raised during: base.views.Accueille class User(AbstractUser): instructor = models.BooleanField(default=False) # ... other fields class Course(models.Model): title = models.CharField(max_length=255) description = models.TextField() instructor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='courses') # ... other fields class Home(View): def get(self, request): try: courses = Course.objects.select_related('instructor').all() # ... rest of the view -
How to Deploy Django API without zero downtime?
I have a Django API project that I need to deploy using CI/CD on an on-premises Linux server without requiring maintenance. because previous build user can using without downtime how to deploy new build version. I need to Deploy Django API without downtime to Linux server -
How can i use yopmail as django email backend?
I Wanted to use yopmail as my Django Email Service can anyone know about how to use this? Using yopmail service as django email backend. Curious to learn different email service in django. yopmail is one the temporary mail service so wanted to learn such service in my django project in staging. -
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 …