Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to redirect a non-www subdirectory to that subdirectory with the www domain?
I'm new to web hosting and I'm currently having trouble redirecting subdirectories that don't have the www subdomain. Typing example.com/subdirectory/ just goes to https://www.example.com/ I want it to go to from example.com/subdirectory/ to https://www.example.com/subdirectory/ I'm using django, pythonanywhere, and namecheap. I've already looked a lot online but there just doesn't seem to be any examples with someone using django, pythonanywhere and namecheap. There were some cases where using htaccess solved the problem, but I don't think it's compatible with django? -
Having issues with my Django form ; returning invalid
I keep getting form.is_valid return false from my Django form Here is my views.py def book_bus(request): if request.method == 'POST' : form = bookbusform(request.POST) if form.is_valid() : cd = form.cleaned_data current_loc = cd['current_location'] destination = cd['Destination'] departure = cd['departure_date'] User = get_user_model() if 'booknow' in request.POST : user = User.objects.get(phone_number=request.user.phone_numbe> booking = Booking.objects.create(current_Location = current_l> booking.created_by = user booking.save() return redirect('payonline') else : user = User.objects.get(phone_number=request.user.phone_numbe> booking = Booking.objects.create(current_Location = current_l booking.created_by = user booking.save() return redirect('home') else : return redirect('error-page') else : form = bookbusform() context = { 'form' : form } return render(request,'bookbus.html',context) My forms.py file class bookbusform(forms.Form) : current_location = forms.ChoiceField(choices = Bus_Terminal.objects.values_list("id","name"),widget = forms.Select(attrs={"class":"selec> Destination = forms.ChoiceField(choices = Bus_Terminal.objects.none(),widget = forms.Select(attrs={"class":"select","id":"Des"})) departure_date = forms.DateField(widget = forms.DateInput(attrs={"type":"date","min":min_date,"max":max_date})) -
Django Updateview in modal
im not so confirm in Django, and Im trying to change some parts from a existung project to my wishes. The existing project is not from me, I downloaded from Github here: https://github.com/AliBigdeli/Django-Smart-RFID-Access-Control/ I added in Card management one new field in models.py class UIDCard(models.Model): ... ammount = models.DecimalField(max_digits=8, decimal_places=2, default=0) ... Also added in the folder dashboard/api/serializers.py the price in class CardReaderSerializer Now I changed some parts in templates/card-management.html Added the field "ammount" in the genral overview, is showing me the Database value Added a Pay button, open a new Modal window, the plan is to add some money on it. The enterred value is saving on the Database, but with two issues. first, I cant see the existing values from the Database in the formfields prefilled. Like in the edit part second, the Update button is saving the value but the modal window is not closing I cant find the problems in the code, can somewhre helping me please The complete changed .html file: {% extends 'dashboard/base.html'%} {% block content %} <div class="d-flex"> <div> <h1 class="mt-4">Cards</h1> </div> <div class="ms-auto mt-4"> <button type="button " class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#CreateFormModal" id="CreateDevice"> Add Card ID </button> </div> </div> <hr> <div class="table-responsive" style="height: … -
Papertrail logs not displaying for Django app in production
I have a Django app that is deployed to production using Heroku. I am currently trying to integrate papertrail logging but no logs are being sent to production. At this point I am at a total loss as to why my logs are not going through. I am not using papertrail as a Heroku addon, but am using the web interface. This is what my LOGGING setting is in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'papertrail': { 'level': 'INFO', 'class': 'logging.handlers.SysLogHandler', 'address': ('logsX.papertrailapp.com', XXXXX), 'formatter': 'verbose', }, }, 'loggers': { '': { # This is the root logger, capturing logs from any logger. 'handlers': ['console', 'papertrail'], # Start with 'console' for development. Add 'papertrail' for production. 'level': 'DEBUG', 'propagate': True, }, }, } NOTE: In my code the address is correct, I am of course redacting it in this post. In my views.py I have the following code: import logging logger = logging.getLogger(__name__) def index(request): logger.warning('test') I have deployed this to production but I see no logs coming in. I am at a loss … -
How to display data from api json for django
I'm trying to create a weather website in django but I don't know exactly how to get apis data and display it in my templates. following a tutorial I arrived at this view: from django.http import HttpResponse import requests def weatherdata(request): response = requests.get('https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m,relative_humidity_2m,precipitation').json() context = {'response':response} return render(request,'home.html',context) and this html: <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <strong>LATITUDE AND LONGITUDE</strong> {{latitude}} {{longitude}} </body> </html> considering the following lines in the api: {"latitude":52.52,"longitude":13.419998, and the result was, basically nothing. No error but no information was printed in the screen how do I solve this? -
How to save logs, to S3Boto3Storage, with Django Logging
I need to save my logs to a file on dedicated storage (using S3BotoStorage). I haven't found any working solution yet. Does anyone know how to make it work? I need to incorporate something similar to logging.handlers.RotatingFileHandler with backups. This is my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard', 'filters': [], }, 'file': { 'level': 'INFO', 'class': 'fundamental.cdn.backends.LogsRootS3BotoStorage', 'formatter': 'standard', 'filename': 'logs.log', }, }, 'loggers': { logger_name: { 'level': 'INFO', 'propagate': True, 'handlers': [],#['file'], } for logger_name in ('django', 'django.request', 'django.db.backends', 'django.template', 'articles') }, 'root': { 'level': 'DEBUG', 'handlers': ['console'], } } this is cdn.backed from storages.backends.s3boto3 import S3Boto3Storage ... class LogsRootS3BotoStorage(S3Boto3Storage): location = "logs" file_overwrite = False -
How do i use external file storage for user uploaded files in Django
I have deployed my django application on vercel and the mysql database is deployed on Clever Cloud. I have used the Clever Cloud File Storage (FS Bucket) service, free tier to store user uploaded files and images but I am not able to make it work I get the error: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Here is my configuration DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage' SFTP_STORAGE_USE_AGENT = False # Avoid using insecure key agent authentication SFTP_STORAGE_HOST = 'bucket-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxx-fsbucket.services.clever-cloud.com' SFTP_STORAGE_USERNAME = 'username@bucket_name' # Use correct IAM user with access # Retrieve password securely from environment variable (highly recommended) SFTP_STORAGE_PASSWORD = 'xxxxxxxxxxxx' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-fsbucket.services.clever-cloud.com/portfolio/' I cant seem to find the issue. I am open to use any other file storage if it's free -
Encountering Server Error (500) During Website Deployment Without Clear Error Messages On Render.com
During deployment on Render.com, I encounter a Server Error (500) without receiving any warnings or errors in the logs. Interestingly, only pages that don't interact with the database load successfully, suggesting potential issues with database permissions or connection configurations. Unfortunately, the lack of detailed error messages makes it challenging to pinpoint the exact cause of the problem. Seeking insights and solutions to resolve this deployment issue. from pathlib import Path import os import dj_database_url # 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.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', default='your secret key') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = 'RENDER' not in os.environ ALLOWED_HOSTS = [] RENDER_EXTERNAL_HOSTNAME = os.environ.get('RENDER_EXTERNAL_HOSTNAME') if RENDER_EXTERNAL_HOSTNAME: ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalogoApp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'panelBM.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'panelBM.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases … -
how to show image in html
#models.py class Contact(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=False) photo = models.ImageField(upload_to='static/photos/', null=True, blank=True) def __str__(self) -> str: return f'{self.name} {self.photo}' #forms.py class ContactForm(forms.Form): name = forms.CharField(required=True, label='Name') photo = forms.ImageField(required=False, label='Photo') #views.py def post(self, request:HttpRequest)->HttpResponse: # print(request.POST) form = ContactForm(request.POST, request.FILES) if form.is_valid(): Contact.objects.create(name=form.cleaned_data['name'], photo=form.cleaned_data['photo']).save() #. . . class ContactDetail(DetailView): model = Contact #contact_detail.html <ol> <b>{{object.name}}</b><br> Photo: <img src="{{object.photo}}" width="55%"> </ol> I've this but when I want t see that contact, there's no image in page. what I should do? it just shows this atajan(name) -
Troubleshooting Plesk: Resolving Python Django App Issues
I recently encountered a frustrating issue while attempting to deploy my Python Django 3 application on a hosting server running Plesk on CentOS. Every time I tried to access the application URL, I was greeted with a discouraging 403 error. Despite my efforts to tweak various Apache, nginx, and HTTPS directives within Plesk, as well as experimenting with Passenger, none of my attempts seemed to resolve the issue. Has anyone else faced a similar challenge, and if so, how did you manage to overcome it? I'm eager to hear any suggestions or insights that could help me get my Django app up and running smoothly. Thanks in advance for any assistance! -
Django migration error for custom model where if tried it make migraiton shows table doesn't exist
I have created login register app for that I have used django django.contrib.auth.models import abstractuser and used inbuilt user model and added more fields into it and then in setting.py add this line "AUTH_USER_MODEL = 'login_register.loginRegister'" and when tried to make migrations it shows error that login_register doesn't exist, I undestood that it is trying to refernce it before it's initialization but i don't understand I am just trying to makemigrations and not call it. Tried to makemigrations and migrate into database but getting error table doesn't exist -
Dump Web Client Sending the same post request MANY times to Django server
I am developing an acquisition server for an IoT application, I am using Django web framework for this task. (Acquisition server is a server that recieves messages from a client "a hardware Microcontroller in my case" and saves the data it recieves to the database) The client I am working with is a closed source controller, so I cannot modify how it behaves. I only have control over my acquisition server. The problem: The controller is sending the same request with the same data multiple times in a row and django is opening a new thread for every request. I want Django to handle the request of the controller and not open a new thread for the controller (the controller is dump), after Django handles the request it sends a confirmation messages to the controller and the controller would send next request. How can I achieve that in Django? I do not know where to start or how to look for an answer for my question. -
how to combine models in a view?
I have two models, submission and additionalinfo. class Submissions(models.Model): STATUS=() CAUSE=() def create_new_ref_number(): return str(random.randint(1000000000, 9999999999)) submissions_number_id = models.CharField(max_length=10,blank=True, unique=True, default=create_new_ref_number,editable=False) client = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, related_name='submissions') contents = models.TextField() status = models.CharField( max_length=30, choices=STATUS, default='1') submissions_supervisor = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, related_name='submissions_supervisor') contractors = models.ManyToManyField(User, related_name='contractors') submissions_cause=models.CharField(max_length=30, choices=CAUSE, default='3') execution_date = models.DateField(null=True, blank=True) details_planned_service=models.TextField(null=True) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) class AdditionalInfo(models.Model): submission = models.ForeignKey(Submissions, on_delete=models.CASCADE, related_name='additional_info', default='') contents = models.TextField() submissions_supervisor = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, related_name='additional_info_supervisor') created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) The website displays all submissions according to the date they were scheduled, and it is also possible to click the mini preview which opens the MODAL WINDOW, and here is the problem because the data from the submission model is all displayed, but I don't know how to add additional information to it. def Schedule(request): report=Submissions.objects.filter(status=4) staff = User.objects.filter(groups__name='Realization') list=[0,1,2,3,4,5,6,7,8,9,10,11,12,13] dt=[] for l in list: date=datetime.date.today() next_date = date + timedelta(days=l) dt.append(next_date) schedule_dict=dict() schedules=Submissions.objects.all() for schedule in schedules: schedule_dict[schedule] = schedule.contractors.all() context={ 'report':report, 'next_data':dt, 'staff':staff, 'schedules':schedules, } return render(request, 'staff/work_schedule.html', context) {% for d in next_data %} <table class="table table-striped table-hover"> <div style="width: 100%;background-color: rgb(0, 0, 0);"><span style="color: white;font-weight: 800;font-size: 14px;">{{d|date:'l'}}</span> <span style="color: rgb(178, 220, 7);font-weight: … -
expected str, bytes or os.PathLike object, not tuple how to solv
say me fast Hello sir this is my error ohter django same project good working then all copy and paste this code other project then show this error this error two days but not solving here are many django developer you have idea and say me where is error which models or views or admin TypeError at /admin/post/post/add/ expected str, bytes or os.PathLike object, not tuple enter image description here -
is there any one having solutions to reverse and redirect to pages in Django after submitting the form or update
I redirect to goals list by clicking the category ID and I want to add an other goal and then redirect to goals list but display errors NoReverseMatch at /planningCycle/goal_update/15/ Reverse for 'planning' with no arguments not found. 1 pattern(s) tried: ['planningCycle/planning/(?P<id>[0-9]+)/\\Z'] enter image description here my views.py enter image description here my urls.py enter image description here my html -
Connect flutter app to django using websockets
I'm completely new to WebSockets, so basically I'm trying my best to create in my Django project and integrate it in my Flutter project. The idea is to have a rooms and the participants of those rooms to be able to chat. So, in my Django settings, I have added 'daphne' in the installed apps, I have created my chat consumers like so: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): # scope is the request parameters passed from the url route self.room_id = self.scope['url_route']['kwargs']['room_id'] self.room_group_name = 'chat_%s' % self.room_id # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): # Leave room await self.channel_layer.group_discard(self.room_group_name, self.channel_name) That is how my room and Message models look: class Message(models.Model): """Chat message model""" body = models.TextField() sent_by = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) class Meta: ordering = ('created_at',) def __str__(self): return f'{self.sent_by}' class Room(models.Model): class Meta: verbose_name_plural = "Rooms" unique_id = models.CharField( max_length=8, primary_key=True, editable=False, unique=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=101, null=True, blank=True) password = models.CharField(max_length=50, blank=True, null=True) users = models.ManyToManyField(User, through='UserRoom', related_name='users_room') messages = models.ManyToManyField(Message, blank=True) def __str__(self) -> str: return str(self.name) I have added the consumers to my urls: path('ws/<str:room_id>', chat_consumers.ChatConsumer.as_asgi()), And configured my … -
How can I save my photo that is taken from form ImageField in database
#models.py class Contact(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=False) photo = models.ImageField(upload_to='static/photos/', null=True, blank=True) def __str__(self) -> str: return f'{self.photo}, {self.name}' #admin.py @admin.register(Contact) class ContactAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'photo'] #forms.py class ContactForm(forms.Form): name = forms.CharField(required=True, label='Name') photo = forms.ImageField(required=False, label='Photo') #views.py def post(self, request:HttpRequest)->HttpResponse: form = ContactForm(request.POST) if form.is_valid(): Contact.objects.create(name=form.cleaned_data['name'], photo=form.cleaned_data['photo']).save() And then when I've created contact with that photo, there's name but no src of photo in admin panel. It seems like it haven't been saved. What could be the problem of that..? -
Pagination not working with django-tables2
I don't get any pagination at all, it is supposed to be automatic. I am using django_mail_admin for the models Table code class IncomingTable(tables.Table): class Meta: model = IncomingEmail template_name = "django_tables2/bootstrap.html" fields = ("id", "subject",) View code, there seems to be some duplication of models class IncomingMail(SingleTableView): table_class = IncomingTable queryset = IncomingEmail.objects.all().order_by("-id") template_name = "incoming.html" Any help would be great, thanks. -
List of all values in Django model attribute
I am creating an e-commerce website and I want to allow the user to filter the search results by various products specs. I want to return in my API a meta dictionary containing all the values each product attribute has. For example, if the user searches for 'iPhone', the response should look like this: { 'data': { ... }, 'meta':{ 'options':{ 'model': ['iPhone 12', 'iPhone 13', 'iPhone 14'], 'manufacturer': ['Apple'], ... } } } Here is my model for reference: class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=False, blank=False) description = models.TextField(max_length=2048, null=False, blank=True) price = models.FloatField(null=False, blank=False, default=0) model = models.CharField(max_length=255, null=False) manufacturer = models.CharField(max_length=255, null=False) seller = models.CharField(max_length=255, null=False) So far i have tried using this, where products is my QuerySet of Product entities after applying the 'iPhone' search: products.values_list('model') The problem with this is that it returns a QuerySet, but I want a list. I was hoping there is a one-liner that I don't know about. -
In Django Admin, how do I reference reverse foreign key relations for `list_display`?
In my app, we may have new languages or dialects of languages appear at any time, and text written in one language or dialect may need to be translated into another. That's why we handle text by relating text in different languages into "families" (i.e. the translation set into different languages). class StringFamily(models.Model): id = models.AutoField(primary_key=True) # plus some other fields class String(models.Model): id = models.AutoField(primary_key=True) # the reference to StringFamily family = models.ForeignKey(StringFamily, null=False, on_delete=models.CASCADE) # other important stuff language = models.ForeignKey(Language, on_delete=models.DO_NOTHING) dialect = models.ForeignKey(Dialect, null=True, on_delete=models.SET_NULL) text = models.TextField(null=False) Unfortunately this complicates using the Django ORM. When we hit a problem with the app, we're generally saved by using raw SQL to deal with this setup. But I also want to use the Django admin, and I don't see any SQL workaround there. In particular, there are all sorts of models that have some text that may appear in multiple languages, like so: class Element(models.Model): id = models.AutoField(primary_key=True) element_role = models.ForeignKey(ElementRole, null=False, on_delete=models.RESTRICT) string_family = models.ForeignKey(StringFamily, null=True, on_delete=models.SET_NULL) # plus more fields What I want is to be able to something like this (everything here works except "display_english_string"): class ElementAdmin(admin.ModelAdmin): list_display = ("element_role", "display_element_type", "display_english_string") This works … -
Goal: How to dynamically create field named status to be display end user side using django?
I am working on a personal web page that ideally would tell me the status of my groceries for example: expired and unexpired based on some input such as date bought and expiration date printed on the products. I am new to the django framework but I been learning a lot online and using chatgpt, youtube and reading articles to explain some of the concepts and how to use it. I am currently stuck on why the code that dynamically generates the status field in the function get_context_data(), at the moment it works but I am confused why it works since it was a suggestion by chatgpt. I am unsure why do I have to write context['allproducts'] = productStatus instead of simply create a context['status'] = productStatus then call status in the variable for all elements in the Products model. The datatype for the productStatus is Queryset but it appears to be behaving as a dictionary when I use the assignment operation for product.status. I you could explain why it is actually working would be amazing since it is not obvious to me how the productStatus is receving this product.status column. Is this the best practice on how to dynamically … -
Django - HTTP ERROR 405 - Method Not Allowed (GET): /account/logout
When try to click logout button, shows this text In urls.py from django.urls import path from users_app import views from django.contrib.auth import views as auth_views urlpatterns = [ path('register', views.register, name='register'), path('login', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout', auth_views.LogoutView.as_view(template_name='logout.html'), name='logout') ] In logout.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %} <title>Logged Out - Taskmate</title> {% endblock title %} {% block content %} <div class="container"> </br> <h4>Logged Out Of TaskMate, Thank You For Using Us!</h4> </div> {% endblock content %} type here When clicked on to Logout button, expected to appear the text as "Logged Out Of TaskMate, Thank You For Using Us!"your text -
How to make a Custom Response class in Django REST framework
I am using django rest framework api as the backend for my project. I treid making a custom Response class for the project and put together the code shown below: class CustomResponse(Response): def __init__(self, error=None, message=None, data=None, status_code=None, *args, **kwargs): self.error = '' if error is None else error self.message = {} if message is None else message self.data = {} if data is None else data self.status_code = status.HTTP_200_OK if status_code is 1 else status.HTTP_400_BAD_REQUEST return super().__init__(data = {'error': self.error, 'message': self.message, 'data': self.data, 'status_code': self.status_code}, status=self.status_code, *args, **kwargs) Is there a better way to do this? Like should I expand some more on this CustomResponse class or should I create a completely new one in some other way? The CustomResponse is to be used for returning serialized data from Views that are made by inheriting the APIView. I was using Response directly for this and I wanted to make something that allows me to add extra details easily according to whether the Response was for something that succeeded or if it had some sort of errors. I searched a lot and everything that I found was similar to the code I made above. But I feel like something … -
How can I handle user authentication in my Remix app if I'm running a DRF backend?
I have Remix app which which relies on a django rest framework api as the backend for data(including users'). In the API, I use JWT to handle user authentication but now that i want to connect it to my remix app, I'm not sure of the best approach on implementing this jwt authentication from the frontend(remix app) or if I should be using a different authentication backend entirely in my API. I've created a sign up page that sends user credentials to the sign up endpoint which creates the user and to sign in, I also send user credentials to the login endpoint which returns the access and refresh tokens. For now, I save this tokens in localStorage(i know this is insecure) and include them in the headers of any requests to endpoints with auth or permissions. Also, in the root module of my remix app, i get the access token(if avaliable) from LS and make a request to the endpoint to get the current user context and pass this into the root component as context. This is stressfull, inefficient and insecure. What is a better, more secure approach to achieve this? -
Django FileResponse crashes with large files
...I have a Django application with a lot of data and a MariaDB database running on a Raspberry Pi (OS = Debian 12). The application uses Daphne as Webserver because there are also Django Channels components in there (Websocket). Now I want to implement a backup feature, that automatically dumps the database, zips together the dump with the other data files and has the browser automatically download the ZIP-file. So I made a view for the download: def downbackup(request): if request.user.is_superuser: filename = '../temp/backup/backup.zip' sourcefile = open(filename, 'rb') return FileResponse(sourcefile) else: return(HttpResponse('No Access.')) That view is called from the relevant template via url and verything is fine. Until we meet large files in real live. In this case (filesize around 6 GB) Daphne immediatly stops operation, and the Raspi crashes so deep that I have to switch power on and of. Also, in Monitorix I see huge memory consumption spikes after these crashes. But there is no error message in the Daphne logs, in the Django logs (incl. debug-setting) nor in the journalctl. Nginx (the reverse proxy) reports an uplink timeout (504). I think I learned from the Django documentation the FileResponse buffers the file to avoid memory consumption, but …