Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I use "taggit" django module, It work fine in my local server,when I push code to server I got 500 internal servere errror
As I said everything is working on my system, but when I pushed code to my server (I replace my app directory with a new updated code directory and manually add "taggit" in my installedapp in settings.py file) after that I run "sudo service apache2 reload". I got 500 Internal server error. I set the debug=True in settings.py but nothing comes up in browser still 500 Internal server error. I read a lots of solution but nothing worksfor me. When I undo the chnages every thing work fine website comes live. I install a taggit module using pip as shown below. ubuntu@ip-172-31-35-150:/var/www/mysite$ pip3 install django-taggit Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django-taggit in /home/ubuntu/.local/lib/python3.6/site-packages (1.3.0) Requirement already satisfied: Django>=1.11 in /usr/local/lib/python3.6/dist-packages (from django-taggit) (3.0.7) Requirement already satisfied: asgiref~=3.2 in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-taggit) (3.2.10) Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-taggit) (2020.1) Requirement already satisfied: sqlparse>=0.2.2 in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-taggit) (0.3.1) Then I try to import the module from shell It get imported. ubuntu@ip-172-31-35-150:/var/www/mysite$ python3 manage.py shell Python 3.6.9 (default, Jul 17 2020, 12:50:27) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from taggit.models import Tag … -
Url forwarding in a Google App Engine project to firebase hosting
I have a GAE project created using Django. I also have a static website for the project's homepage hosted on firebase. If someone visits www.myproj.com, they should see the static webpage hosted on firebase. If someone visits www.myproj.com/j/64gj37, they should see the response delivered by the django project. I am looking for something like this: configuration: url: / redirect_to: https://myproj-homepage.firebaseapp.com/ url: /(.+)$ project: myproj-django What should be the configuration for dispatch.yaml and app.yaml? I am currently using a simplistic app.yaml # [START django_app] runtime: python37 default_expiration: "4d 5h" handlers: # This configures Google App Engine to serve the files in the app's # static directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to the main app. # It is required when static routes are defined, but can be omitted # (along with the entire handlers section) when there are no static # files defined. - url: /.* script: auto # [END django_app] -
How do I drop a database of Postgres in Django?
So during migration I ran into an error saying I don't have a certain column. I've revised my code but I keep getting the same error and realized that I need to drop the database itself (tried deleting all migrations files except init.py). But I can't figure out how. FYI, the project name is mvp, and the app where the problem occurred is qanda. I want to preserve the db in other apps in my project. HOW DO I DROP A SPECIFIC DATABASE? Thank you very much. -
Best way to make an Auth API call from inside Django Template?
I have a Django template which displays information from the twitch API. I'm making the API call within views, but it's severely impacting the load time of the page. What I would like to do instead is make the call from the template html instead, so that I can load the page faster and update what needs to be updated asynchronously after the rest of the page has loaded. I've tried looking up how to do it, one option may be using ajax or js to make the call directly from the page, but that risks exposing the API key. Is there another way? Without exposing the API key to the client? -
how to get values from keys in django forms.MultipleChoiceField
I am Saving the details by keys in multiplechoiceFiled In form.py from django import forms from .models import PData class DocumentForm(forms.ModelForm): MY_CHOICES = ((1, 'C'), (2, 'Java'), (3, 'Python'),(4,'.Net'), (5,'Java Script'), (6,'Angular js'), (7,'Ajax'), (8,'Go'), (9,'Ruby'), (10,'C++'), (11,'SQL'), (12,'Php'), (13,'PowerShell'), (14,'Django'), (15,'MangoDB')) skills = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=MY_CHOICES) class Meta: model = PData fields = '__all__' It will be saved in the database like this now I want to display skills but through the values In views.py from django.shortcuts import render,HttpResponse from .models import PData from .forms import DocumentForm def Dis_Data(request): data=PData.objects.all() return render(request,'dispaly_data.html',{'users_data': data}) def insert_d(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.skills = ','.join(form.cleaned_data['skills']) form.save() return HttpResponse('DATA INSERTED SUCCESSFULLY') else: form = DocumentForm() return render(request, 'insert.html', {'form': form}) return HttpResponse('INSERTED PAGE') please help me thanks in advance -
How to use select_related with Django create()?
class Parent(models.Model): # some fields class Child(models.Model): parent = models.ForeginKey(Parent) species = models.ForeignKey(Species) # other fields I have a function like this: 1. def some_function(unique_id): 2. parent_object = Parent.objects.get(unique_id=unique_id) 3. new_child = Child.objects.create(name='Joe', parent=parent_object) 4. call_some_func(new_child.parent.name, new_child.species.name) In the line 4, a db query is generated for Species. Is there any way, I can use select_related to prefetch the Species, so as to prevent extra query. Can it be done while I use .create(). This is just an example , I am using many other fields too and they are querying the DB every time. The only way I can think is after line 3 using this code: child_obj = Child.objects.select_related('species').get(id=new_child.id) -
Uploading a .py file through a form in django, and importing the functions defined in it in view.py
I want to upload a .py file that contains some defined functions through form input method. Then in view.py i want to use that functions which are defined in this uploaded python file. What would be the method of importing those funtions. i am able to upload the file, but dont know how to import the functions. -
ValueError at /accounts/segui/2/1/ <Follower: Follower object (None)> instance isn't saved. Use bulk=False or save the object first
I needed a following system, so I tried to rely on already written codes. The views weren't there and I tried to write them alone, but I couldn't. I am new to Django and sorry I don't know English well. Thanks in advance! models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Follower(models.Model): follower = models.ForeignKey(User, on_delete=models.PROTECT, related_name='following') following = models.ForeignKey(User, on_delete=models.PROTECT, related_name='followers') class Meta: unique_together = ('follower', 'following') def __unicode__(self): return u'%s segue %s' % (self.follower, self.following) views.py def AddFollowerView(request, pk, id): user = get_object_or_404(User, pk=pk) userFollow = get_object_or_404(User, id=id) user.following.add(Follower(following=userFollow)) user.following.save() return HttpResponseRedirect('/stories/') def RemoveFollowerView(request, pk, id): user = get_object_or_404(User, pk=pk) userFollow = get_object_or_404(User, id=id) follower= Follower follower.objects.bulk_create([ follower(follower=user, following=userFollow), ]) return HttpResponseRedirect('/stories/') urls.py path('follow/<int:pk>/<int:id>/', AddFollowerView, name="add-follower"), path('not-follow/<int:pk>/<int:id>/', RemoveFollowerView, name="remove-follower"), Sorry if this question has been asked several times, but I have not been able to understand how to solve it. -
Permission Error while adding Raster layer in Django framework using Django-Raster package
I was trying to load a raster layer using Django-raster module. But often i am getting the Permission error saying "The process cannot access the file because it is being used by another process" I am using Windows OS. Any idea how to resolve it. -
Django Search in many to many field
I am trying to create a search in my Django Rest Framework application I have a table of follower and following via one model called: UserFollowing and the code is: class UserFollowing(TimeStampedModel): user_id = models.ForeignKey( User, related_name="following", on_delete=models.CASCADE, blank=True) following_user_id = models.ForeignKey( User, related_name="followers", on_delete=models.CASCADE, blank=True) @property def username(self): profile_instance = Profile.objects.get(user=self.user_id) username = profile_instance.profile_username return username @property def name(self): profile_instance = Profile.objects.get(user=self.user_id) name = profile_instance.name return name class Meta: unique_together = ("user_id", "following_user_id") ordering = ["-user_id"] def __str__(self): return str(self.id) Here everything works fine but in my following list API, I am appending username and name of the user. When I am getting a list of follower using: paginator = PageNumberPagination() query_set = UserFollowing.objects.filter(user_id=request.user.id) context = paginator.paginate_queryset(query_set, request) serializer = UserFollowingSerializer(context, many=True) Now I want to search via the result my serializer.data look like: { "count": 2, "next": null, "previous": null, "results": [ { "id": 233, "username": "Username1", "user_profile_image": "url", "name": "CDE", "is_active": true, "created_at": "2020-07-25T06:00:31.786154Z", "updated_at": "2020-07-25T06:00:31.786185Z", "user_id": 88, "following_user_id": 53, "is_following": true }, { "id": 49, "username": "username", "user_profile_image": "URL", "name": "ABC", "is_active": true, "created_at": "2020-07-15T08:32:35.352484Z", "updated_at": "2020-07-15T08:32:35.352517Z", "user_id": 88, "following_user_id": 144, "is_following": true } ] } So based on my output how can I search a … -
Why do I keep getting "column _id does not exist" error in Django?
I keep getting column qanda_question.category_id does not exist error. Let me show you my model. class QuestionCategory(models.Model): category = models.CharField(max_length=20, default="", primary_key = True) def __str__(self): return(str(self.category)) class Question(models.Model): number = models.IntegerField(primary_key=True) question = models.CharField(max_length=1000, default="") category = models.ForeignKey(QuestionCategory, on_delete=models.CASCADE, null=True, default=None) def __str__(self): return (str(self.category)+" "+str(self.number)+". "+str(self.title)) I've tried deleting all the migrations files in migrations folder except init.py, but the error persists. What do you think is the problem? +++ FYI, The directory where the models.py is located is qanda. -
If else statements use in Django
I am trying to use {%if %} {%else%} statement with following 3 condition in Django template but it execute every time else condition with any true if or else if condition. Please help me and tell me the solution of my problem as soon as possible. I tried: <form class="form-container" style="" method="POST">{% csrf_token %} <div class="h1 text-center text-light" style="text-decoration:underline">Doctors List</div> <br> <table class="table table-bordered"> <thead class="text-center"> <tr> <th>Name</th> <th>Mobile No</th> <th>Department</th> <th>Status</th> <th>Last Date</th> <th>Today</th> <th>Total Attend</th> <th colspan="2">Attendance</th> <th>Leave</th> <th colspan="2">Actiion</th> </tr> </thead> <tbody> {% for d in data %} <tr> <td>{{d.Name}}</td> <td>{{d.Mobile_No}}</td> <td>{{d.Department}}</td> <td class="text-center">Active</td> {% for dt in dtaa %} {% if dt.Mobile_No == d.Mobile_No and dt.Status == 1 %} <td>{{dt.Present_Date}}</td> <td class="text-center">Present</td> <td class="text-center">{{dt.Attendance}}</td> {% elif dt.Mobile_No == d.Mobile_No and dt.Status == 0 %} <td>{{dt.Present_Date}}</td> <td class="text-center">Absent</td> <td class="text-center">{{dt.Attendance}}</td> {% elif dt.Mobile_No == d.Mobile_No and dt.Status == 2 %} <td>{{dt.Present_Date}}</td> <td class="text-center">Join</td> <td class="text-center">{{dt.Attendance}}</td> {% else %} <td></td> <td class="text-center">Not Join</td> <td class="text-center"></td> {% endif %} {% endfor %} <td><a href="Present/{{un}}" class="btn btn-block form-control btn-success font-weight-bold" style="width:40px; height:30px; font-size:13px">P</a> <td><a href="/Absent" class="btn btn-block form-control btn-success font-weight-bold" style="width:40px; height:30px; font-size:13px">A</a></td></td> <td class="text-center">Working </td> <td class="text-center"><a href="" style="text-decoration:none; color:white;">Edit</a><td class="text-center"><a href="" style="text-decoration:none; color:white">View</a></td></td> </tr> {% endfor %} </tbody> … -
Static files not being served on AWS Lightsail
After 2 days of trying multiple tutorials & reading StackOverflow, I'm calling for help! The setting: The development version is running smoothly on the AWS Lightsail server. It's during the production deployment that I'm running in continuous problems with the static files. The application runs on the appointed subdomain but it's missing all the JS/CSS/images/... I have followed the official docs but to no avail. 1/ https://docs.bitnami.com/aws/infrastructure/django/get-started/deploy-django-project/ 2/ https://docs.bitnami.com/aws/infrastructure/django/get-started/deploy-django-project/ My Folder Tree with relevant files: Project - conf - httpd-app.conf - httpd-prefix.conf - Django2Tutorial - settings.py - wsgi.py - Solar - static - static (after running collectstatic function in terminal,-it includes the admin, Solar statics) My settings: STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' DEBUG = False ALLOWED_HOSTS = ['54.169.172.***'] wsgi.py file import os import sys sys.path.append('/opt/bitnami/apps/django/django_projects/Project') os.environ.setdefault("PYTHON_EGG_CACHE", "/opt/bitnami/apps/django/django_projects/Project/egg_cache") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoTutorial2.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() My conf files : 1. httpd-app.conf file <IfDefine !IS_DJANGOSTACK_LOADED> Define IS_DJANGOSTACK_LOADED WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP} </IfDefine> <Directory "/opt/bitnami/apps/django/django_projects/Project/DjangoTutorial2"> Options +MultiViews AllowOverride All <IfVersion >= 2.3> Require all granted </IfVersion> WSGIProcessGroup wsgi-djangostack WSGIApplicationGroup %{GLOBAL} </Directory> Alias /static "/opt/bitnami/apps/django/django_projects/Project/static" <Directory "/opt/bitnami/apps/django/django_projects/Project/static"> Require all granted </Directory> WSGIScriptAlias / '/opt/bitnami/apps/django/django_projects/Project/DjangoTutorial2/wsgi.py' 2. httpd-prefix.conf file # Include file RewriteEngine On RewriteCond "%{HTTP_HOST}" ^ec2-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3})\..*\.amazonaws.com(:[0-9]*)?$ RewriteRule "^/?(.*)" "%{REQUEST_SCHEME}://%1.%2.%3.%4%5/$1" [L,R=302,NE] Include … -
Using Ajax to passing multiple value and fetching data in view to export it in excel in Django
View.py def export(request): if request.is_ajax(): ourid = request.GET.getlist("terid") print() print(ourid) print("hi") print() Case_Detail = Case_Info_Resource() for i in ourid: print(i) queryset = Case_Info.objects.filter(id=i) dataset = Case_Detail.export(queryset) response = HttpResponse( dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="persons.xls"' print("breakpoint") return response Ajax Script <script> $(document).ready(function () { $('#Download').click(function () { var list = []; $("input:checkbox[name='checkbox']:checked").each(function () { list.push($(this).val()); }); $.ajax({ url: '/Account_Manager/Download/', type: 'GET', data: { 'terid': list }, traditional: true, dataType: 'html', success: function () { alert("The best cricketers are: " + list.join(", ")); } }); }); }); </script> So, Ajax wants us to return the value in HttpResponse but I need to pass the response normally in order to download the excel which I am creating. I think I checked all the possible answers and struggling with it from the last 3 days. Thank you in advance for any help, suggestions, or edit. -
Pass primary key in success_url in Delete Class view in django
views.py, I have class views class Delete_Post(DeleteView): model= Post template_name='dlt.html' #success_url= '/profile/1' -> working #reverse_lazy('user:posts') -> working success_url = reverse_lazy('profile/pk=id')-> not working But to get id , I tried 1.request.user.id request is not defined error 2.object.author.id object has no attribute author -
Django Enforce unique combination of pair of foreign keys
So let's say I have the following Django models defined: class Model(models.Model): model_id = models.IntegerField(default=0, unique=true) content = models.TextField() class ModelRelation(models.Model): relation_id = models.IntegerField(default=0, unique=true) model_id1 = models.ForeignKey(Model, on_delete=models.CASCADE) model_id2 = models.ForeignKey(Model, on_delete=models.CASCADE) With a regular UniqueConstraint in the constraints option of the Meta class, a foreign key pair of model_id1 = 1 and model_id2 = 2 is allowed to coexist with a foreign key pair of model_id1 = 2 and model_id2 = 1. How do I implement a behaviour like in the first answer to Postgresql enforce unique two-way combination of columns in Django? How do you even make an unique index in Django? -
Querying n-items based on per column
These are my models: from django.db import models class A(models.Model): # fields class B(models.Model): a = models.ForeignKey(A) # fields I have some items from model A: items = A.objects.filter(some_column=some_value) Now I want 2 model B objects for each object in items. If there are 5 objects in items then I want total 10 objects from model B, 2 model B objects for each object of model A. Hope I made my requirement clear. I tried some queries, but ended up with querying model B for each model A object. If it is not possible with ORM, then I can use raw query as well. -
Django cart function
I'm trying to create a cart function, in which when the products are in the cart and their order status is shipped, the function should change the status from shipped to delivered, subtract the cart product amount from product stock and empty the cart model. So far I have only been able to change the status and my subtraction seems to be not working properly as it's only subtracting from 1 product in cart despite having 2. @shared_task() def update_inventory(): cart = Cart.objects.all() order = Order.objects.all() for item in cart: Order.objects.filter(status='Shipped').update(status='Delivered') Product.objects.filter(product_name=item.product).update(stock=F('stock') - item.amount) order.status = 'Delivered' item.delete() return None class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField(default=1) def __str__(self): return str(self.product) class Product(models.Model): stockId = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100) product_type = models.CharField(max_length=100) stock = models.IntegerField(default='0', blank=True, null=True) def __str__(self): return self.product_name class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) cart = models.ManyToManyField('Cart') status_choices = (('Processing', 'Processing'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), status = models.CharField(max_length = 100, choices = status_choices) -
ModelChoiceFilter gives "Select a valid choice. That choice is not one of the available choices." when submitted
I am using django-filters to filter my products based on brand. When i submit my form, i get "Select a valid choice. That choice is not one of the available choices." I used ModelChoiceFilter because the docs said that is it suitable for ForeignKey relationships. Form successfully rendered as checkboxes as intended on product.html: form successfully rendered When form is submitted with checkboxes selected, error arises: ModelChoiceFilter gives error Surprisingly when i changed the filter to ModelMultipleChoiceFilter, I did not get a "Select a valid choice. That choice is not one of the available choices." error. I wonder why ModelChoiceFilter would throw this error. here is my code: models.py class Brand(models.Model): bool_choices = ( (True, 'Yes'), (False, 'No'), ) name = models.CharField(max_length=30) def __str__(self): return f"{self.name}" class Product(MPTTModel): parent = TreeForeignKey('self', blank = True, null = True, related_name = 'children', on_delete=models.CASCADE) name = models.CharField(max_length=50) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="brand") #one to many relationship between Brand and Product class category = TreeManyToManyField(Category, blank = True) filters.py import django_filters from product.models import Product, Category, Brand from django.db import models from django import forms class BrandFilter(django_filters.FilterSet): brand = django_filters.ModelChoiceFilter(queryset= Brand.objects.all(), widget=forms.CheckboxSelectMultiple, empty_label = None, to_field_name = 'name') class Meta: model = Product fields … -
How to create/update/view two modal class with one serializer
I have two model class. I want to create/update/view both model class with one serializer. I have tried but its not working. Here is my modal class: class PackageQuantity(models.Model): comp_code = models.ForeignKey( 'core.SensorDevice', on_delete=models.SET_NULL, null=True ) quantity = models.IntegerField() class PackageComponent(models.Model): pkg_code = models.CharField(max_length=255) package = models.ForeignKey( 'PackageQuantity', on_delete= models.CASCADE, null=True ) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) Any help will be highly appreciated. Thanks -
How to update data for logged-in users by using modelviewset in django
I try to operate the create method when generating the data for the first time and the update method if the data already exists after identifying the data of the currently logged-in user. So I wrote the code as follows but it doesn't work the way I want it to. views.py class arduinoViewSet (ModelViewSet) : serializer_class = arduinoSerializers permission_classes = [IsAuthenticated] def get_queryset (self) : queryset = arduino.objects.filter(name=self.request.user) return queryset def perform_create (self, serializer) : serializer.save(name=self.request.user) def perform_update(self, instance, validated_data): instance.title = validated_data['name'] instance.save() serializers.py class arduinoSerializers (serializers.ModelSerializer) : name = serializers.CharField(source='name.username', read_only=True) class Meta : model = arduino fields = ['pk', 'name', 'temp', 'humi'] How do I write code to implement it the way I want? -
Django - How to post date values
I am getting an error Object of type 'date' is not JSON serializable when trying to sumit a form with a date field. I have a simple form with a datefield set as shown: date_of_birth = forms.DateField() I have a jquery datepicker in the html and the relevant code is shown below: Html: <!-- DOB --> <div class="row"> <div class="form-group col-md-4"> {{ wizard.form.date_of_birth.label_tag }} {{ wizard.form.date_of_birth|add_class:"datepicker"}} </div> </div> Javascript: <script> $(function() { $(".datepicker").datepicker({ changeMonth: true, changeYear: true, minDate: -400000, maxDate: -0, yearRange: '1920:' + new Date() }); $(".datepicker").datepicker("option", "showAnim", "clip"); }); </script> I understand I have to change the date value to a string but I have no clue where exactly I change that before I submit. How can I get this working? -
Django Multiple response of queryset
In the search, I am trying to search the database through title using this code product_title = request.GET.get('txtSearch') status = product.objects.filter(title__icontains=product_title) And there is another column called product_Subcategory how to get that column using this data? when I try to print status I got this queryset <QuerySet [<product: OnePlus 7T Pro (Haze Blue, 8GB RAM, Fluid AMOLED Display, 256GB Storage, 4085mAH Battery)>]> In which there is no product_Subcategory...if anyone can help...Thanks. -
Error while trying to open file with finders "Located outside of base path.."
I am trying to attach an image to an email, but Finders is not finding it. I tried changing path, moving image, creating a new folder.. nothing seems to work. For some reason, the base path is showing the .virtualenv path, while I have It worked on my local server, but as soon as I put it on a staging server (online), I get this error in console when trying to send email: django.core.exceptions.SuspiciousFileOperation: The joined path (/home/ubuntu/project/static/images/email_imgs/fld-logo.png) is located outside of the base path component (/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/contrib/admin/static) Here is my .py to send an email: message = EmailMultiAlternatives( subject="**Test Email", body=html_message, from_email="direct@project.com.au", to=email_to_list, *args ) message.mixed_subtype = 'related' message.attach_alternative(html_message, "text/html") message.attach(image_data("fld-logo.png")) def image_data(image): with open(finders.find(settings.MEDIA_ROOT+'/images/email_imgs/'+image), 'rb') as f: logo_data = f.read() logo = MIMEImage(logo_data) logo.add_header('Content-ID', '<image>') return logo -
Django + Nginx X-Accel-Redirect Not Working
I've been trying to make this work on my own for months now, but I just couldn't figure out what is wrong with my code, I'm running django + gunicorn + nginx, nginx it's set as a reverse proxy to gunicorn and I want download files using nginx which is the best way instead of leaving all the work to django backend which is slow. Anyway here is my sites-available config: server { listen 8080; server_name 127.0.0.1; client_max_body_size 10M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myuser/Dev/myproject/src; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/myuser/Dev/myproject/src/myproject.sock; } location /attachments/ { internal; alias /home/myuser/Dev/myproject/src/media/files; } } I tried adding ~^ and ^~ to the location block, changing the name, using absolute paths, nothing worked my urls.py (here the important url is 'attachment/download/int:id'): from django.urls import path from .views import ( issue_detail_view, issue_update_view, issue_list_view, issue_upload_attachment, issue_download_attachment, issue_delete_attachment ) app_name = 'issues' urlpatterns = [ path('<int:id>', issue_detail_view, name='issues_detail'), path('<int:id>/update', issue_update_view, name='issues_update'), path('<int:id>/list', issue_list_view, name='issues_list'), path('<int:id>/attachment', issue_upload_attachment, name='issues_upload_attachment'), path('<int:id>/attachment/delete', issue_delete_attachment, name='issues_delete_attachment'), path('attachment/download/<int:id>', issue_download_attachment, name='issues_download_attachment') ] and my views.py: def issue_download_attachment(request, *args, **kwargs): id_ = kwargs.get('id') attachment = Attachment.objects.get(id=id_) filename …