Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert django request.body (bytes) into json
I have a class based view in which a put function and trying to get request.body into json. from django.views import View import json class StudentView(View): def put(self, request): body = request.body #b'name=Arpita+kumari+Verma&roll=109&city=USA' json_body = json.loads(body) # JSONError 'expecting dict values but given bytes object' # I want something like this # { # 'name':'Arpita kumari Verma', # 'roll':'109, # 'city':'USA', # } json_dumped_data = json.dumps(json_body) return HttpResponse(json_dumped_data, content_type="application/json") -
Django template won't respond to css file , worked briefly yesterday
It is exactly how it sounds. My main goal is to make the css file work with django template so I can design my templates. Yesterday I tried and initially my folder structure was wrong. I placed static folder in myapp folder. Didn't work. I tried putting it in templates folder. It only worked when I had 2 static folders both in myapp and templates folder. Realized it isn't a working solution. I placed a single static folder with a css file in it in mysite folder, at the same level with myapp folder and everything seemed to work. Satisfied I left at that. Today I came back to it and it stopped working. It seems to be frozen. Not responding to the new codes. Old colors are showing but new colors aren't, which is odd. Tried changing the old colors, it won't change. Literally my css file has a class name .intro where I changed the color from purple to red, my template still showing purple which I set yesterday. My template shows no error and all the texts and divs I am adding are updating with no issue.Kind of lost where I may have gone wrong. Certainly don't … -
How to open a modal when moving a page
The currently implemented code shows the modal when clicking the button. However, I would like the modal to be displayed when moving to the main page after logging in. (using Django) JavaScript's window.open is not what I want because it prints a new window. I want the modal window to be displayed automatically when the main page is reached upon successful login. Is there a way? [index.html] <div class="modal fade" id="quality" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Quality</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body row"> <div class="col-sm-12"> {% include 'pages/quality_POPUP.html' %} </div> </div> </div> </div> <button type="button" class="btn pull-right" data-toggle="modal" data-target="#quality">POP UP</button> -
Get sales totals per account using model property in django
Okay I thought I can google my way out of this but I am stuck. Desired results are Account_name Total local sales 1802.50 int sales 0.00 from my models class Account(models.Model): account_number = models.IntegerField(unique=True, null=True, blank=True, default=None) account_name = models.CharField(max_length=200, null=True, blank=True, unique=True) class Sales(models.Model): account_name = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='incomes') amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) def sales_total(self): sales_total = Income.objects.values('account_name').order_by('account_name').annotate(sales_total=Sum('sales__total')) return sales_total so in my template when I do {% for account in accounts %} <tr> <td>{{ account.sales_total }}</td> </tr> {% endfor %} I get Account_name Total local sales <QuerySet [{'account_name': 3, 'sales_total': Decimal('1802.5')}]> int sales <QuerySet [{'account_name': 3, 'sales_total': Decimal('1802.5')}]> -
cannot import name 'Channel' from 'channels'
I am using python version==3.8.10 and Django==2.2 and channels==3.0.4 . I am getting error from channels import Channel ImportError: cannot import name 'Channel' from 'channels' (/home/kritik/py38_djanngo2.2_new/lib/python3.8/site-packages/channels/init.py) Can anyone help me on this ? -
after login having error 'Anonymous User' object has no attribute '_meta'
I m new in Django m creating a signup form if submit the form the data is stored success fully but I m having a error in redirection or login view.py from Blog.forms import SignupForm from django.contrib.auth import authenticate,login from django.http import HttpResponseRedirect def signup_form(request): form=SignupForm() if request.method=='POST': form=SignupForm(request.POST) if form.is_valid(): user=form.save() user.refresh_from_db() # load the profile instance created by the signal user.save() raw_password = form.cleaned_data.get('password') user = authenticate(username=user.username, password=raw_password) login(request, user) return HttpResponseRedirect('home/') return render(request,'blog/signup.html',{'form':form}) redirecting in setting file setting.py LOGIN_REDIRECT='home/' LOGOUT_REDIRECT_URL='/logout' my form file look like that forms.py from django.contrib.auth.models import User class SignupForm(ModelForm): class Meta: model=User fields=['username','first_name','last_name','email','password'] labels={'username':' Enter User Name','password':' Enter Password','email':'Enter Email','first_name':'Enter First Name','last_name':'Enter Last Name'} widgets={'password':forms.PasswordInput,'username':forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Your User Name'}), 'password':forms.PasswordInput(attrs={'class':'form-control','placeholder':'Enter Your Password'}), 'email':forms.EmailInput(attrs={'class':'form-control','placeholder':'Enter Your Email'}), 'first_name':forms.TextInput(attrs={'class':'form-control','placeholder':'Enter First Name'}), 'last_name':forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Last Name'}) } urls.py path('signup/',views.signup_form,name='signup/'), 'Anonymous User' object has no attribute '_meta' -
Django post request field always null
My post request from React frontend to Django backend won't work and I'm not sure why. It always says that "question" is null. I know there to be a question already in the database with a primary key id of 19. Quiz.js: const createAnswerSubmission = () => { submit(questionIndex); const data = { "question": quiz.question[questionIndex].id, "answer_choice": answerSelected[questionIndex], "user": window.localStorage.getItem("user") } const url = "http://localhost:8000/api/submittedanswer/"; axios.post(url, data, {headers: { Authorization: `Token ${window.localStorage.getItem('auth_token')}`, Accept: "application/json", 'Content-Type': 'application/json', } }).then(function (response) { console.log(data) }) .catch(function (error) { console.log(data); alert(error); }); } The console log shows the following: {question: 19, answer_choice: 4, user: '1'} And the request payload shows: {question: 19, answer_choice: 4, user: "1"} Yet I am getting some error: IntegrityError at /api/submittedanswer/ null value in column "question_id" of relation "api_submittedanswer" violates not-null constraint DETAIL: Failing row contains (123, 4, null, 1). models.py: //... class Question(models.Model): pt = models.ForeignKey(PT, on_delete=models.CASCADE, null=True, blank=True, related_name = 'pt') section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True, blank=True, related_name = 'section') question_type = models.CharField(max_length=20) number = models.IntegerField() stimulus = models.CharField(max_length = 1000) question = models.CharField(max_length = 400) answer = models.ManyToManyField(AnswerChoice) correct_answer = models.IntegerField(default = 0) def __str__(self): return "PT " + str(self.pt) + " Section " + str(self.section) + " … -
Use python par file with gunicorn
I want to use a django app packaged as a par file generated via https://github.com/google/subpar with gunicorn. Is this possible? -
Factory boy field not getting expected value
I am using factory boy to generate data for my django application. It is a tennis matches app which has player one and two as shown in below class. Either of it will be a winner which will be store in winner_one field. I am getting some third player name in this field instead of player one or two. That player is also present in table. Please advise what would be the best way to fix this? class MatchFactory(factory.django.DjangoModelFactory): class Meta: model = Match player_one = factory.SubFactory(UserFactory) player_two = factory.SubFactory(UserFactory) league = factory.Iterator(League.objects.all()) type = fuzzy.FuzzyChoice(Match.MATCH_CHOICES, getter=lambda c: c[0]) winner_one = random.choice([player_one, player_two]) start_date = fuzzy.FuzzyNaiveDateTime( datetime.today() + relativedelta(months=1), datetime.today() + relativedelta(months=3) ) end_date = start_date -
How to open URL when clicking push notification using firebase-admin in Python Django
I'm going to use python django's firebase-admin to send a notice to FCM push notification when the app is in the background state. When the user clicks the push notification, the iOS/Android app attempts to open the url of the notice. How should I pass this url value? noticeView.py: from firebase_admin import credentials, messaging import firebase_admin class noticeCreateView(View): def post(self, request, *args, **kwargs): title = request.POST.get('title') content = request.POST.get('content') push = request.POST.get('push') if push: key = '....FCM Server Key...' cred = credentials.Certificate('./serviceAccountKey.json') default_app = None if '[DEFAULT]' not in firebase_admin._apps: default_app = firebase_admin.initialize_app(cred) else: default_app = firebase_admin._apps['[DEFAULT]'] if default_app is not None: topic = 'notice' message = messaging.Message( notification=messaging.Notification( title=title, body=sentence, ), apns=messaging.APNSConfig( payload=messaging.APNSPayload( aps=messaging.Aps(alert=messaging.ApsAlert( title=title, body=content, )), ), ), topic=topic ) try: response = messaging.send(message) print(response) except Exception as e: print('Push Fail', e) return HttpResponseRedirect(reverse('notice_list')) -
Postgresql - "ERROR: character with byte sequence 0xf0 0x9f 0x98 0x84 in encoding "UTF8" has no equivalent in encoding "WIN1252""
So I was querying on my Heroku server with this query // Command to get into postgres heroku pg:psql // Query SELECT * FROM cheers_post; then I get this error ERROR: character with byte sequence 0xf0 0x9f 0x98 0x84 in encoding "UTF8" has no equivalent in encoding "WIN1252" I don't know what character 0xf0 0x9f 0x98 0x84 is in UTF8. This error isn't super explicit so I'm not really sure what the issue is or how to fix it. Anyone experience this? Something interesting is when I query the cheers_post table via a Django API endpoint it returns Post.DoesNotExist error. -
Django & Celery: no such table
I am attempting to create a couple tasks with Celery that post data to a Django model, I have everything functioning except for some reason the Celery tasks are not able to see the table even though it exists in the DB and Django can post data to it. This is happening with PostgreSQL, it works when using SQLite3. Has anyone encountered this type of issue and how were you able to solve it? tasks.py -------- # tasks from __future__ import absolute_import, unicode_literals from celery import Celery from celery import app, shared_task # scraping import requests from bs4 import BeautifulSoup import json from datetime import datetime import lxml from rss_feed_scraper.models import PressReleases # logging from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @shared_task(serializer='json') def save_function(article_list): for article in article_list: try: PressReleases.objects.create( title=article['title'], description=article['description'], link=article['link'], image_url=article['image_url'], published=article['published'], source=article['source'] ) except Exception as e: print('failed at inserting article') print(e) break @shared_task def prnewswire_rss(): article_list = [] try: print('Starting the scraping tool') r = requests.get('https://www.prnewswire.com/rss/all-news-releases-from-PR-newswire-news.rss') soup = BeautifulSoup(r.content, features='lxml') articles = soup.findAll('item') for a in articles: title = a.find('title').text description = a.find('description').text # Get Link link = str(a) i = link.find("<link/>") j = link.find("<guid") media_content = a.find('media:content') image_url = None if media_content: image_url = … -
Iterable list in Django HTML?
I want to use bootstrap to make a carousel using D.R.Y. methods. my idea (and it may not even be feasible) is to have a list or dictionary and cycle through image locations. Here's what I've written so far. <div class="carousel-inner"> {% with images = ['gyro.jpeg', 'pizza.jpeg', 'soup.jpeg', 'brocpizza.jpeg' ,'dessert.jpeg'] %} {% for image in images %} <div class="carousel-item active" data-bs-interval="10000" style="background-image:url({%static {image}%})"> <div class='container'> <section class='time'> <h3><strong>HOURS</strong></h3> <h3><strong>Monday - Saturday</strong></h3> <h3><strong>11 a.m. - 9 p.m.</strong></h3> </section> <div class='headline'> <h1>Title</h1> <h2>Menu</h2> </div> <section class='address'> <h3> <strong>NAME</strong> </h3> <h4>Phone</h4> <h4>Address</h4> <h4>City</h4> </section> </div> </div> {% endfor %} {% endwith %}``` -
Getting a 400 Bad Request Error After GCP App Engine Deployment of Django App
So I have a Django App which has its views connect to a BigQuery where it would pull data from. I want to deploy the web app to a GCP App Engine and have followed the instructions that are stated on GCP App Engine Website. I have successfully created the SQL instances and can run the web app locally. I deploy the app using gcloud app deploy, it says that it is successfully deployed. When I try to open the web app on the browser gcloud app browse, it just returns me a 400 Bad Request Error. I'm kinda lost as I don't know what I'm missing during deployment plus I don't know which part of my code I should be putting on here so do comment below what I need to be posting in order to guide you to help me and I will update the post. Another thing is that, since I'm pulling data from the BigQuery, locally I have this JSON file which has all the credentials needed for the BigQuery API and I access it in the settings.py as such: os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/Users/user/Documents/website/bq-api.json' The thing is I'm wondering if I should be including this inside the … -
Django Filters 'str' object has no attribute '_meta'
I am creating an page that allows the user to filter a dataset, hit search, and see the results update below. I am getting the following attribute error: 'str' object has no attribute '_meta' and I cannot figure out why this is happening. Any help is appreciated views.py: def week(request): #orders = Pick.objects.get(id=pk_test) orders = Pick.objects.all() #orders = week.order_set.all() myFilter = PickFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'week':week, 'orders':orders, 'myFilter':myFilter} return render(request, 'app/filter_list.html',context) pick_list.html: {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} {% endblock title %} {% block content %} <div style="font-size:24px"> {{ title }} </div> <div style="font-size:14px; margin-bottom:15px"> Click on the arrows on the right of each contestant and drag them up or down to reorder them based on how far you think they are going to go. </div> <form method="get"> {{ myFilter.form }} <button type="submit">Search</button> </form> <ul> <table class="table table-hover" id="table-ajax" style="background-color: white;"> <thead style="background-color: #de5246; color:white; border-bottom:white"> <tr> {% comment %} <th></th> {% endcomment %} <th style="width: 50px; text-align: center;"></th> <th>{{ object_list|verbose_name:'field:name' }}</th> <th>{{ object_list|verbose_name:'field:hometown' }}</th> <th>{{ object_list|verbose_name:'field:occupation' }}</th> <th>{{ object_list|verbose_name:'field:age' }}</th> <th>Progress</th> <th style="width: 160px; text-align: center;">Rank</th> </tr> </thead> <tbody class="order" data-url="{% url 'cms:reorder' … -
Processing Tiff and saving to Django ImageField
The program I'm trying to write takes in a multipage Tif file/stack and processes it by: Changing tiffile to numpy arrays Taking numpy arrays and turns them into tensors Processes tensors and turns them back to numpy arrays Finally takes said numpy arrays and turns it back into a tiff stack. My Code: models.py : from django.db import models import numpy as np import tensorflow as tf from PIL import Image from django.core.files.base import ContentFile from django.core.files.uploadedfile import InMemoryUploadedFile # Create your models here. class TiffModel(models.Model): name = models.CharField(max_length=450) image = models.ImageField(blank = True, null = True) def __str__(self): return self.name def img (self): return self.image def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) images = [] tensors = [] processedArrays = [] tiffStack = [] # Read tif, convert each page into arrays in images[] for i in range(img.n_frames): img.seek(i) images.append(np.array(img)) # Read every numpy array, convert to tensorflow, process by dividing by 2 for x in images: tensorX = tf.convert_to_tensor(x) processedTensor = tf.math.divide(tensorX,2) tensors.append(processedTensor) # Convert back to numpy array for x in tensors: processedArrays.append(x.numpy()) # Convert to tif for x in processedArrays: tiffStack.append(Image.fromarray(x)) img = tiffStack[0].save(self.name + ".tiff", compression="tiff_deflate", save_all=True, append_images=tiffStack[1:]) img.save(self) The issue I'm running … -
Django equivalent of ASP.NET Parameter Binding or Ruby on Rails Action Controller Parameters
I'm wondering what's mentioned in the title. This are links to the examples mentioned, regarding other techs: ASP.NET Parameter Binding Ruby on Rails Action Controller Parameters Currently I'm building an API using DRF and using custom code in views or serializers validate methods to validate parameters, like this: class AnimalWriteSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = '__all__' def validate_dicose_category(self, value): raise serializers.ValidationError('Dicose Category cannot be set manually.') Is there a better way? -
Heroku throwing error H10 for my Django site
When I go to my site it tells me to run heroku logs --tail, and when I do that I get: 2022-01-16T05:23:01.227344+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=riseupontario.herokuapp.com request_id=49558b9a-5030-4ed9-bf0a-cc8642531c44 fwd="204.128.182.15" dyno= connect= service= status=503 bytes= protocol=https 2022-01-16T05:23:01.528171+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=riseupontario.herokuapp.com request_id=41626c63-e4e6-4e72-90e7-c0e36d3c928d fwd="204.128.182.15" dyno= connect= service= status=503 bytes= protocol=https I can't find anything on how to fix this. Help! -
HTML Not Picking Up Bootstrap & Won't Combine
I am creating an page that allows the user to filter a dataset, hit search, and see the results update below. Whenever I updated my week function to pick_list.html instead of filter_list.html, I get the error below. My filter_list.html doesnt show any bootstrap visuals or colors from the rest of my app, just a plain list. The pick_list.html shows a search button, but no search fields and zero data. Why am I struggling so much to combine these two? views.py: def week(request): #orders = Pick.objects.get(id=pk_test) orders = Pick.objects.all() #orders = week.order_set.all() myFilter = PickFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'week':week, 'orders':orders, 'myFilter':myFilter} return render(request, 'app/filter_list.html',context) pick_list.html: {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} {% endblock title %} {% block content %} <div style="font-size:24px"> {{ title }} </div> <div style="font-size:14px; margin-bottom:15px"> Click on the arrows on the right of each contestant and drag them up or down to reorder them based on how far you think they are going to go. </div> <form method="get"> {{ myFilter.form }} <button type="submit">Search</button> </form> <ul> <table class="table table-hover" id="table-ajax" style="background-color: white;"> <thead style="background-color: #de5246; color:white; border-bottom:white"> <tr> {% comment %} <th></th> {% … -
django celery delay function use guest user
Hello I want to use celery tasks in my Django project When I run the celery -A proj worker -l INFO all good it connects to the rabbitmq server But I have a problem when I run the task add.delay(1, 1) I get a response (403) ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile. In the logfile I can see 2022-01-16 23:15:51.898981+00:00 [erro] <0.1093.0> PLAIN login refused: user 'guest' - invalid credentials I understand celery delay function using the wrong user guest and not saar my file in my project celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() settings.py CELERY_TASK_TRACK_STARTED = True CELERY_BROKER_URL = 'amqp://saar:1234567s@localhost' init.py from .celery import app as celery_app __all__ = ('celery_app',) tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y my packages: Django 3.2.11, celery 5.2.3, flower 1.0.0, django-celery-beat 2.2.1 What can I do to fix it? -
Django and HTMX I am looking for not "hacky" way to update class of link that calls HTMX request. Like "refresh-self" or something along those lines
I have a problem with HTMX in Django. I basically have two important components on page. List of categories and content that is being shown after you click on category. I was working nicely with just standard htmx "out of the box". But I started having problems when I wanted to add active css class on category link after you click it (to show user where he is currently). I did a lot of experiments with hx-swap-oob and hx-swap but the only thing that work was this: (it is the most relevant part of the code) <div class="col-sm-4"> <div class="card"> <div class="card-body" hx-boost="true" hx-target="#manual_results"> <div id="manual_categories"> {% include 'partials/manual_categories.html' %} </div> </div> </div> </div> <div class="col-sm-8"> <div id="manual_results"> {% include 'partials/manual_entries_list.html' %} </div> </div> and in manual_entries_list.html: <some html results> <div id="manual_categories" hx-swap-oob="true"> {% include 'partials/manual_categories.html' %} </div> Each category has simple if statement in django template code that is checking if it is selected (based on url path.) And it is working, thing is, on the first request the categories are rendered twice (which is logical since I have 2 includes on the same HTML). After I select one category, everything goes back to normal because HTMX "starts to … -
Django - Uploaded image gets saved twice: under original and validated name
I'm trying to solve a problem. On image file upload, I want to rename the file and resize it. I came up with a method below. I managed to get the image resized and saved under a valid name. Unfortunately the file gets saved twice, also under the invalid name. And the invalid one is stored in my object. How can I fix this? Thanks in advance class SparePartImages(models.Model): sparepart = models.ForeignKey('SparePart', on_delete=models.CASCADE) image = models.ImageField(upload_to='spare-part/', blank=True, null=True) def save(self, *args, **kwargs): super(SparePartImages, self).save(*args, **kwargs) max_size = settings.IMAGE_MAX_SIZE file = Image.open(self.image) (width, height) = file.size if (width/max_size < height/max_size): factor = height/max_size else: factor = width/max_size size = (int(width/factor), int(height/factor)) file = file.resize(size, Image.ANTIALIAS) file.save(removeAccent(self.image.path)) -
Why is the response i recieve at the front-end undefined
Why am i getting an when sending the post request.When i pass in the response body a string i dont get errors and it works perfectly fine but when i pass an complex element like this in json-like form it doesnt work. def main(request): if request.method == 'GET': return Response({ "name": "PPP", "lastName": "UUU" }) elif request.method == 'POST': try: data = request.body data = json.loads(data) P.pom1=data['poz1'] P.pom2=data['poz2'] CompMove() return Response({"poz1":P.pom1, "poz2":P.pom2}) except: return Response({"GRESKA"}) - List item -
How to display a StackedInline item from a Model in Django?
i want to get the value of my field "is_verified" from aStakedInline model of my Post model class PostAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'words', 'date', 'is_verified') list_filter = ('date', 'author') def is_verified(self, obj): # HERE MY UNKNOWN CODE TO GET IS_VERIFIED VALUE FROM VerifiedPost Model def words(self, obj): return len(obj.content.split()) class AccountInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'Profiles' class PostInline(admin.StackedInline): model = VerifiedPost can_delete = False verbose_name_plural = 'Verified' models.py If anyone can help me -
Django download images from s3 bucket
i want to download the files i uploaded to the s3 bucket but i can't. Whenever i click on the things i want to download nothing happens and when i right click and open in new tab it shows me this link: "statichttps://airport-comsroom.s3.us-east-2.amazonaws.com/uploaded_files/Adobe_Photoshop_2021_v22.5.3.561_x64_2021_MULTILANG_RUS_rutracker-6148156.torrent?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential="cant show this"%2F20220117%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20220117T000020Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=2f6a8924ac5d9ced877d572bc901b40cce85f8dfd90cb70b1d64483e4bf369b4" settings.py AWS_ACCESS_KEY_ID = 'Can't show this' AWS_SECRET_ACCESS_KEY = 'Can't show this' AWS_STORAGE_BUCKET_NAME = 'airport-comsroom' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_SIGNATURE_VERSION= 's3v4' AWS_S3_ADDRESSING_STYLE = 'virtual' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' html file {% for file in dic.user_files %} <a href="static{{file.files.url}}" class="files" download> <div class="flex-file"> <p class="file-text">{{file.files}}</p> <img src="{%static 'Images/File.png'%}" class="file-image"alt=""> </div> </a> {% endfor %} I don't know if the download at the end of the a tag is the problem or even the correct way to do it. but this is what I got. it downloads fine when I serve the static files locally. and the file can be anything like word, pdf, excel, ect. please tell me if you need to view other pages.