Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create 2 objects from separate models with a single serializer and also retrieve them from the database with a single serializer in Django RF?
I have 3 models: Maker, Item and MakerItem that creates the relation between the items and their makers: class Maker(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=100) class Item(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=100) class MakerItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) item_id = models.ForeignKey(Item, on_delete=models.CASCADE) maker_id = models.ForeignKey(Maker, on_delete=models.CASCADE) the items can have a random amount of makers. I want to create both the Item and the MakerItem objects at the same time with a single set of data, for example if a Maker with id = "abcd" already exists, and I go to /item and send a POST request with the following data: { "name": "item1", "makers": [ { "maker_id": "abcd" } ] } I want the serializer to create the Item object and the MakerItem object. I have achieved this, with the following setup: views.py class ItemListCreate(ListCreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer serializers.py class ItemSerializer(serializers.ModelSerializer): class MakerItemSerializer(serializers.ModelSerializer): class Meta: model = MakerItem exclude = ['id', 'item_id'] makers = MakerItemSerializer(many=True) class Meta: model = Item fields = ['id', 'name', 'makers'] def create(self, validated_data): maker_item_data = validated_data.pop('makers') item_instance = Item.objects.create(**validated_data) for each in maker_item_data: MakerItem.objects.create( item_id=check_instance, maker_id=each['maker_id'] ) return check_instance but when Django tries to return the created … -
Restricting Python type hints to values from a tuple
One of my methods takes a status argument that's used in a filter(). This argument is related to a model field defined like this : STATUS_CHOICES = ( (1, _("draft")), (2, _("private")), (3, _("published")), ) class MyModel(Model): status = models.PositiveSmallIntegerField(_("status"), choices=STATUS_CHOICES, default=1) I'd like to use Python's type hints in order to make its definition clearer. I could probably do something like : def my_method(status: int): ... But the status has to be included in STATUS_CHOICES. Can I make this hint more restrictive and limited to STATUS_CHOICES values? -
Django update profile
Hi guys I hope you'll be Great I have a question this day about how to update a profile in my Django app. the problem is that when I fill the spaces in the form and I click the save changes button the content doesn't update the info in the admin to the profile I'll appreciate your feedback thanks you can see it in https://github.com/edisonjao5/Django2App Or here is the code in profiles app models.py from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from sorl.thumbnail import ImageField class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile' ) SOCIAL = ( ('twitter', 'Twitter'), ('facebook', 'Facebook'), ('instagram', 'Instagram'), ('youtube', 'Youtube'), ('github', 'Github'), ) First_Name = models.CharField(max_length=30) Last_Name = models.CharField(max_length=30) Username = models.CharField(max_length=30) image = ImageField(upload_to='profiles') Password = models.CharField(max_length=30) Social = models.CharField(max_length=30, choices=SOCIAL) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def update_user_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.views.generic import DetailView, View, FormView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Profile from .forms import UpdateProfileForm class UpdateProfileView(LoginRequiredMixin, FormView): http_method_names =['get', 'post'] template_name = 'profiles/update.html' form_class = UpdateProfileForm success_url = '/' def dispatch(self, request, *args, **kwargs): self.request = request return … -
Can't query with Select2 in Django
I try to use Select2 API for JQuery, but I'm having issues with displaying the returned results. I want to be able to search the results I'm getting from my Ajax request. It gives me 0 errors, and I believe I followed the documentation correctly. When I log the returned data from the Ajax I also get the correct data back. What am I doing wrong that I can't see the results inside the select2 input field when searching? This is my Jquery code: $('.radiocheck2').on("click", function(){ console.log("test"); $('.nummerplaat').select2({ minimumInputLength: 2, placeholder: 'Nummerplaat', dataType: 'json', ajax: { url:getallnummerplaten, method: 'GET', data: function (params) { return { q: params.term, type: 'public' // search term }; }, beforeSend: function(xhr, settings) { if(!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, processResults: function (data) { arrNummerplaten = [] for(i=0; i < data['nummerPlaten'].length; i++){ arrNummerplaten[i] = data['nummerPlaten'][i].nummerPlaat } console.log(arrNummerplaten) return { results: arrNummerplaten, }; }, cache: true } }); }) This is my Django view to retrieve the data: class getAllNummerplaten(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): nummerPlaten = list(Voertuigen.objects.all().values("nummerPlaat")) print(nummerPlaten) nummerPlatenjson = json.dumps(nummerPlaten) return JsonResponse({'nummerPlaten': nummerPlaten }) And this is my template code: <!-- TestCode --> <div style="display:none" id="overzichttankbeurten" class="card shadow mb-4"> <div class="card-header py-3"> … -
django rest knox - get token expiry time from request
I'm using django-rest-knox to authenticate users. The token is stored in a cookie and I use a custom middleware to retrieve it. In addition to that, this middleware sets the cookie everytime a request is done to keep the cookie expiration time updated. Django rest knox, has a method to refresh token expiry time (renew_token) and I want to update my cookie if that field is changed. I tried to adapt the code like this: `class KnoxTokenAuthenticationMiddleware: def _update_cookie(self, request, response): response.set_cookie( settings.KNOX_COOKIE_NAME, request.COOKIES[settings.KNOX_COOKIE_NAME], domain=settings.KNOX_COOKIE_DOMAIN, httponly=settings.KNOX_COOKIE_HTTPONLY, secure=settings.KNOX_COOKIE_SECURE, samesite=settings.KNOX_COOKIE_SAMESITE, max_age=settings.KNOX_COOKIE_MAX_AGE, path=settings.KNOX_COOKIE_PATH, ) return response def __init__(self, get_response): # One-time configuration and initialization. self.get_response = get_response def __call__(self, request): if settings.KNOX_COOKIE_NAME in request.COOKIES: request.Authorization = 'Token {}'.format(request.COOKIES[settings.KNOX_COOKIE_NAME]) response = self.get_response(request) try: current_expiry = request.auth.expiry new_expiry = timezone.now() + settings.REST_KNOX.get('TOKEN_TTL') delta = (new_expiry - current_expiry).total_seconds() logging.basicConfig(level=logging.DEBUG) logging.debug('current expiry: {}'.format(current_expiry)) logging.debug('new expiry: {}'.format(new_expiry)) logging.debug('delta: {}'.format(delta)) logging.debug('refresh interval: {}'.format(settings.REST_KNOX.get('MIN_REFRESH_INTERVAL'))) if delta > settings.REST_KNOX.get('MIN_REFRESH_INTERVAL'): logging.basicConfig(level=logging.DEBUG) logging.debug('update cookie') response = self._update_cookie(request, response) except Exception as e: logging.basicConfig(level=logging.DEBUG) logging.debug(e) else: response = self.get_response(request) return response` The problem is that the request.auth.expiry time does not match the expiry time displayed in database: expiry time from middleware expiry time from database How can i get the expiry time displayed in … -
Using django-admin in Atom Powershell
I am trying for hours but can not get rid of these django error. I have also added the path variable. PS E:\atom\python> django-admin startproject mysite django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject mysite + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
routing DRF with multi slashes lookup_field
i have views (readonlymodel) class Test(ReadOnlyModelViewSet): queryset = Test.objects.all() lookup_field = 'art' serializer_class = TestSerializer @action(methods=['GET'], detail=True) def chars(self, request, art): .... also urls: router = routers.SimpleRouter() router.register(r'api/test', Test) I need lookup_field to work for art with multiple slashes. Example art: "first_product/test" But action chars is also needed. Example 'first_product/test/chars' Examples of queries that should work: 0.0.0.0:8000/api/test/first_product/test 0.0.0.0:8000/api/test/first_product/test/chars 0.0.0.0:8000/api/test/second_product 0.0.0.0:8000/api/test/second_product/chars I tried to do it through lookup_value_regex, but unfortunately it didn't work out that way, either /chars doesn't work, or with /chars works, but it doesn't see without it. Those works either this or that: 0.0.0.0:8000/api/test/first_product/test 0.0.0.0:8000/api/test/first_product/test/chars -
Postgres "relation not found" after running a pg_restore with a Django management command
I'm creating a test database that needs to be sanitized from customer data and needs to stay in sync with our production database. So I have a cronjob in Kubernetes that does a pg_dump, pg_restore and then will run a Django management command to clean the database. The dump and restore work well. I can connect to it via psql and see all tables. The problem is that the management command is failing to find a table relation (literally the first row in the Django script) and if I run a psql right after the restore, it also doesn't find the table, even though I print all the tables to make sure. All this is done through a docker container that has a shell script that basically does the dump, restore and runs the command (unsuccessfully) and the cronjob is connected to the database via a Azure pgbouncer (that's why localhost). This is what I have so far: psql -h localhost -U user -d postgres -c "\i recreate_db.sql" recreate_db.sql: I use this script to close connections, drop and recreate database for simplicity: SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'my_db'; DROP DATABASE my_db; CREATE DATABASE my_db; This works and show … -
ModuleNotFoundError: No module named 'django' even if it is installed (vs code)
I have install django in my virtual environment also activated virtual environment but still it is showing these error python from django.urls import path output Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows PS E:\django\project\telusko> & C:/Users/hp/AppData/Local/Programs/Python/Python39/python.exe e:/django/project/telusko/calc/urls.py Traceback (most recent call last): File "e:\django\project\telusko\calc\urls.py", line 1, in <module> from django.urls import path ModuleNotFoundError: No module named 'django' PS E:\django\project\telusko> -
Django count data apperance in database and send to Django-template
I have this system where i would like to be able to see some staticists over the attendancelog data. I would like to search on the class and the subject and the i get the: attendancename / username_fk the number af times this attendance has attened the subject from the specific class The total amount of times this subject and class has been on different dates the username_fk should also only appear one time My django list view look like this: class AttendanceList(LoginRequiredMixin, ListView): model = AttendanceLog template_name = "./attendancecode/showattendance.html" def get_queryset(self): class_val = self.request.GET.get('class') subject_val = self.request.GET.get('subject') sub = Subject.objects.filter(name=subject_val).first() new_context = AttendanceLog.objects.filter(keaclass_id=class_val, subject_id=sub) return new_context def get_context_data(self, **kwargs): context = super(AttendanceList, self).get_context_data(**kwargs) context['class'] = self.request.GET.get('class') context['subject'] = self.request.GET.get('subject') return context and the result of that is this: My data in the AttendanceLog table look like this so for example the username_fk "nadi6548" has attended "subject_id 2/Large" 4 out of 4 so out from nadi6548 the number 4 stands there and then again 4. I do know the last value of how many time the subject has been there is going to be the same value though the whole list and that is okay. end result: -
Django Shell update objects value
I want to increase the prices by 30% in django shell. models.py: price = models.FloatField(null=True) shell: from product.models import Product Product.objects.all().update(price=price*1.3) error: NameError: name 'price' is not defined -
While I'm trying to set up django server using docker "docker-compose up" its giving Error like this
$ docker-compose up django-ambassador-main_redis_1 is up-to-date Creating django-ambassador-main_db_1 ... error ERROR: for django-ambassador-main_db_1 Cannot create container for service db: user declined directory sharing E:\Office\django-ambassador-main.dbdata ERROR: for db Cannot create container for service db: user declined directory sharing E:\Office\django-ambassador-main.dbdata ERROR: Encountered errors while bringing up the project. -
change font awesome icon in jquery
I have a like button that users jQuery. I want to change the icon based on the like status(outlined heart to filled heart). The issue is when I click like it clears removes the icon pre like: post like: How do I stop it from clearing the icon while still updating the like count, as well as changing the icon class jQuery: <script> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, data.likescount, "like") } else { updateText(this_, data.likescount, "unlike") } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script> like button: <a class="like-btn" data-href='{{ post.get_api_like_url }}' data-likes="{{ post.likes.count }}" href="{{ post.get_like_url }}"><i class="fa fa-heart-o like-heart" aria-hidden="true"></i>{{ post.likes.count }} </a> -
Django STATIC_ROOT not loading files while fully configured
ingestion-dashboard/ ├── apps │ ├── adapter │ ├── authentication | |__init__.py │ ├── static │ │ ├── assets │ │ │-- css │ │ │── img │ │ │── scss │ │ │── vendor │ └── templates │ ├── accounts │ ├── home │ ├── dashboard │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── staticfiles │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt └───staticfiles ├── assets │── css │── img │── scss │── vendor settings.py CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ingestion-dashboard STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'apps/static'), ) The files from apps/static are being copied into STATIC_ROOT successfully, still it is not rendering files from there. In browser , in url i still see ***/static/*** which was in debug mode while I have set DEBUG=FALSE -
'User' object has no attribute 'rank'
So I have this UserProfile model which has ranking system but the problem is its keep getting some attribute error class UserProfile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE,null=True) profile_pic = models.ImageField(blank=True, null=True, default='default.png') bio = models.TextField(null=True,blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) username = models.CharField(max_length=255,null=True,blank=False) rating= models.IntegerField(default=200,null=True,blank=False) major = models.ForeignKey(Major,on_delete=models.SET_NULL,null=True,related_name="major") rank = models.ForeignKey(Rank,on_delete=models.SET_NULL,null=True,related_name="rank") def __str__(self): return self.username and here is its serializer class UserProfileSerializer(serializers.ModelSerializer): profile_pic = serializers.SerializerMethodField(read_only=True) rank = serializers.SerializerMethodField(read_only=True) major = serializers.SerializerMethodField(read_only=True) class Meta: model = UserProfile fields = '__all__' def get_profile_pic(self, obj): try: pic = obj.profile_pic.url except: pic = None return pic def get_rank(self,obj): rank = obj.rank serializer = RankSerializer(rank,many=False) return serializer.data def get_major(self,obj): major = obj.major serializer = MajorSerializer(major,many=False) return serializer.data I dont know why but I am getting this User error Can someone help me please -
Django how to turn a python string into a javascript string and render it to the website
I'm working with Django and in my views I'm sending my page a string of HTML: <p><code>202</code> </p><p>hello world/p> <ul> <li>Goodbye<strong><em>next</em></strong> or <strong><em>happy</em></strong> to go on.</li> </ul> byebye <p>&lt;3</p> However, it gets sent to the page as: var html_smallest_steps = &lt;p&gt;&lt;code&gt;202&lt;/code&gt; &lt;/p&gt;&lt;p&gt;hello world/p&gt; &lt;ul&gt; &lt;li&gt;Goodbye&lt;strong&gt;&lt;em&gt;next&lt;/em&gt;&lt;/strong&gt; or &lt;strong&gt;&lt;em&gt;happy&lt;/em&gt;&lt;/strong&gt; to go on.&lt;/li&gt; &lt; and I get a console error on my page: Uncaught SyntaxError: Unexpected token '&' My views.py is: def displayDict(request): html_ss = """ <p><code>202</code> </p><p>hello world/p> <ul> <li>Goodbye<strong><em>next</em></strong> or <strong><em>happy</em></strong> to go on. </li> </ul> byebye <p>&lt;3</p> """ return render(request, 'chatStream.html', {"html_sss": html_ss}) And chatStream.html is: <p id="chatLine">get this working!!</p> <script> var html_smallest_steps = {{html_smallest_steps}} } setTimeout(myTimeout2, 2000) function myTimeout2() { document.getElementById("chatLine").innerHTML = "html_ss " + html_ss; } </script> -
Display table ordered by row and columns
I am struggling to display an HTML table with data issued from a database. I just retrieve the data using a SELECT and Join multiples tables. Datas are retrieved like : | StorageLocation| Quantity| RiskPhrase| | --- | --- | --- | | Storage1| 10| H225| | Storage2| 4| H225| | Storage1| 3| H226| | Storage3| 3| H226| | Storage4| 3| H226| | Storage4| 3| H300| I want to be displayed like this : | StorageLocation| H225| H225| H226| H300| | --- | --- | --- | --- | --- | | Storage1| 10| 0| 3|0| | Storage2| 0| 0| 4|0| | Storage3| 0| 0| 3|0| | Storage4| 0| 0| 0|4| I really don't know how to deal with this. Is Dataframe the best solution ? Your help will be more than appreciated. Thanks -
Using self.requests.session in forms.ModelForm
I read Django - Access request.session in form but am still almightly confused. I want the default value in one of my form fields to be from self.requests.session (I also tried requests.session). class BookARoomForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(BookARoomForm, self).__init__(*args, **kwargs) self.fields['arrival_date'].initial = self.requests.session['arrival_date'] class Meta: model = RoomBooking fields = ('User', 'title', 'room_type', 'arrival_date', 'departure_date', 'cost') In get_context_data I have tried context['book_a_room_form'] = BookARoomForm(), context['book_a_room_form'] = BookARoomForm(request) and context['book_a_room_form'] = BookARoomForm(self.request). Each time I got a different error. class HotelDetailSlugView(ObjectViewedMixin, DetailView): template_name = "hotel/detail.html" def get_context_data(self, *args, **kwargs): context = super(HotelDetailSlugView, self).get_context_data(*args, **kwargs) context['book_a_room_form'] = BookARoomForm() # Your part form -
How to assign the same value to multiple variables in a class in django models
In the below class orders, I want to assign the same value of weight to the amount class Orders(models.Model): consignment_id = models.IntegerField(primary_key='consignment_id',auto_created=True) order_date = models.DateTimeField(default=timezone.now) weight = models.FloatField() from_place = models.CharField(max_length=20,null=True) destination = models.CharField(max_length=20) amount = models.FloatField(weight) name = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=20, default='Pending') -
Django naturaltime doesn't accept input
Within an API response I receive the following datetime as string: 2021-11-23T15:04:31Z In my Django template I'd like to render this using the naturaltime template tag. However, the template tag just doesn't apply any logic to it and it gets rendered as is. Is there any way to tell Django to format this using the naturaltime? -
Issue with template in django TemplateView
I have 4 types of tickets to display on my dashboard Open,accept,complete and closed i have written the below template view to display all the contexts within single view but if i click on those options on dashboard it displays all status of tickets in all four as in if i click on open tickets it shows all the other status along with open tickets and same goes for other type of tickets as well Dashboard image This is the open ticket url showing all the status instead of only open tickets views.py class DeveloperTicketView(TemplateView): template_name = 'app/ticket_view.html' def get_context_data(self, **kwargs): context = super(DeveloperTicketView,self).get_context_data(**kwargs) context['open_tickets'] = Ticket.objects.filter(status = 'Opened') context['accepted_tickets'] = Ticket.objects.filter(status = 'Accepted',accepted_by = self.request.user) context['completed_tickets'] = Ticket.objects.filter(status = 'Completed',accepted_by = self.request.user) context['closed_tickets'] = Ticket.objects.filter(status = 'Closed',accepted_by = self.request.user) return context Ticket_view.html {% extends 'app/base.html' %} {% block body %} <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>Status</th> <th>Created</th> <th>Title</th> <th>Description</th> </tr> </thead> <tbody> {% for ticket in open_tickets %} <tr> <td><a href="">{{ ticket.id }}</a></td> <td>{{ ticket.status }}</td> <td>{{ ticket.created_by }}</td> <td>{{ ticket.ticket_title }}</td> <td>{{ ticket.ticket_description }}</td> <td><a href="{% url 'accept_tickets' pk=ticket.id %}">Accept</a></td> </tr> {% endfor %} {% for ticket in accepted_tickets %} <tr> <td><a href="">{{ ticket.id }}</a></td> <td>{{ ticket.status … -
Make grafana use JWT token in the local storage
I have a React + DRF web app that has JWT authentication, in which I use djangorestframework-simplejwt. I store access and refresh tokens in the localStorage. Is it possible to use these tokens to authenticate in Grafana? If yes, how can I do that? When I navigate to /grafana (with nginx help), I would like to see that my user in my app to be logged in to the Grafana, by creating the user for Grafana if necessary. -
What are the possible needed algorithms for making a small ecommerce website (with react.js, python-django, mongodb)? [closed]
Recently I've started to work on my project which is somewhat related to the ecommerce website "RED BUBBLE". But I'm confused in what are the algorithms that are needed in fulfilling the basic functionalities of an ecommerce website like Searching a product, recommendations of trending products, and handling the data of every user ? And Which data structure I need to use for an efficient coding and working of the website ? -
Django - Inline formset - How to set current user
-Objective- I need to set, in a Inline Formset, the current user as automatic content of a field of the form. (Currently not working) Version Python 3.9.2 - Django 3.2 Context: I've created a List, where I have some objects(Headers). From the list I can create new headers and access to the detail-page(Detailview)for each of these by using a foreign-key(called by PK-primarykey). In this page I can see more informations about 1 specific header. Each header can have multiple lines of informations that need to be linked to it. The lines are created or updated with (max 4 different) specific Inline Formsets. -Issue and Error- I created the forms that are correctly rendered, but I need to set for each line, a field that automatically gets "current user" as its content. I can't save and receive instead"User cannot be null". I'm unable to find a solutions and tried many things but stuck with this error. Would kindly appreciate any help on how to solve this problem. Thanks in advance, Below some code: URLS.PY from django.urls import path, re_path from fttlapp import views app_name= 'fttlapps' urlpatterns = [ path('fttlapphome2/', views.Fttlapphome2View.as_view(), name='fttlapphome2'), path('fttlogheader/', views.HeadfttlogListView.as_view(), name='headfttlogs'), path('fttlogheader/add/', views.HeadfttlogCreateView.as_view(), name='headfttlogcreate'), path('fttlogheader/<int:pk>/', views.HeadfttlogDetailView.as_view(), name='headfttlogdetail'), path('fttlogheader/<int:pk>/flights/edit/', … -
Nginx download permissions error - Open() failed (13: Permission denied)
I have a webpage with Nginx + Uwsgi + Django where I have an external path called /download to manage the downloads in Django (the user credentials) and the internal path /download-nginx to actually download the files on the directory /var/wwww/download. For the sake of trials, I have tried to do this with my username as well as the default nginx user. With both of them I get a permission denied error on Nginx: open() "/var/www/download/example.txt" failed (13: Permission denied) I have read several other solutions on SO telling that the problem is that the provided user in nginx.conf does not have enough permissions. The thing is that they do have enough permissions: $ sudo -u nginx stat /var File: ‘/var’ Size: 4096 Blocks: 8 IO Block: 4096 directory Device: 802h/2050d Inode: 50331745 Links: 21 Access: (0777/drwxrwxrwx) Uid: ( 996/ nginx) Gid: ( 0/ root) Context: system_u:object_r:var_t:s0 Access: 2021-11-23 11:24:53.329927606 +0000 Modify: 2021-11-23 09:43:29.250244353 +0000 Change: 2021-11-23 11:21:37.151148760 +0000 Also, just in case I have done chmod 777 recursively on directory /var/wwww/download My nginx.conf file is as follows: user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http …