Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
session expiry changes every time
After creating session when i tried to get session the value of expiry date changes every time may I why is this happening. 1st get request - "session_expiry": "2022-02-21T22:42:38.231938Z" 2nd get request - "session_expiry": "2022-02-21T22:53:00.524236Z" 3rd get request - "session_expiry": "2022-02-21T22:53:26.022811Z" In all three cases values are of same session. -
How can i prefill the field in admin site?
I have a model which has two fields file and person who uploaded it when i register my model in admin it should prefill the uploaded field according to the user(only admins) how can i acheive this. models.py: class TemplateModel(BaseModel, SingletonModel): file = models.FileField( upload_to='', validators=[FileExtensionValidator(['', ''])] ) person_uploaded = models.ForeignKey( 'accounts.Account', related_name='', null=True, on_delete=models.SET_NULL, ) -
dj-rest-auth error setting up custom registration serializer
I wrote a custom register serializer according to the docs. I also made a dictionary for REST_AUTH_REGISTER_SERIALIZERS in settings.py and added my REGISTER_SERIALIZER there but I am getting this weird error on the terminal which appears to be coming from dj_rest_auth.registration.app_settings which says that: "RegisterSerializer = import_callable(serializers.get('REGISTER_SERIALIZER',DefaultRegisterSerializer)) AttributeError: 'tuple' object has no attribute 'get' -
django model property not showing up in object
so i have the mentioned model down here which I created a property for , for some reason my properties started to NOT show up in my objects class Cars(models.Model): datetime = models.DateTimeField() source = models.CharField(max_length=200) url = models.CharField(max_length=200) color = models.CharField(max_length=200,null=True,blank=True) year_built = models.CharField(max_length=200,null=True,blank=True) submission = models.CharField(max_length=200,null=True,blank=True) sell_type = models.CharField(max_length=200,null=True,blank=True) chassis = models.CharField(max_length=200,null=True,blank=True) engine = models.CharField(max_length=200,null=True,blank=True) city = models.CharField(max_length=200,null=True,blank=True) id = models.CharField(primary_key=True,max_length=200) title = models.CharField(max_length=200,null=True,blank=True) insurance_left = models.IntegerField(null=True,blank=True) body = models.CharField(max_length=200,null=True,blank=True) gearbox = models.CharField(max_length=200,null=True,blank=True) mileage = models.BigIntegerField(null=True,blank=True) price = models.BigIntegerField(null=True,blank=True) model_year = models.IntegerField(null=True,blank=True) category = models.CharField(max_length=200,null=True,blank=True) car = models.CharField(max_length=200,null=True,blank=True) car_type = models.CharField(max_length=200,null=True,blank=True) neighborhood = models.CharField(max_length=200,null=True,blank=True) img = models.CharField(max_length=300,null=True,blank=True) company = models.CharField(max_length=50,null=True,blank=True) @property def letstestproperty(self): return 'hello world' class Meta: verbose_name_plural = 'Car Records' I output my objects using Cars.objects.values() but there are no property field added to it -
RowNumber Window Query for Hiscores Ranking - Django
I'm trying to build a game hiscore view with rankings for my Django site, and I'm having some issues. The query I have is the following: row_number_rank = Window( expression=RowNumber(), partition_by=[F('score_type')], order_by=F('score').desc() ) hiscores = Hiscore.objects.annotate(rank=row_number_rank).values() The query above works perfectly, and properly assigns each row a rank according to how it compares to other scores within each score type. The result of this is the following: { 'id': 2, 'username': 'Bob', 'score_type': 'wins', 'score': 12, 'rank': 1 } { 'id': 1, 'username': 'John', 'score_type': 'wins', 'score': 5, 'rank': 2 } { 'id': 4, 'username': 'John', 'score_type': 'kills', 'score': 37, 'rank': 1 } { 'id': 3, 'username': 'John', 'score_type': 'kills', 'score': 5, 'rank': 2 } { 'id': 5, 'username': 'Bob', 'score_type': 'kills', 'score': 2, 'rank': 3 } The issue comes in when I want to retrieve only a specific user's scores from the above results. If I append a filter(username="Bob") the query is now: row_number_rank = Window( expression=RowNumber(), partition_by=[F('score_type')], order_by=F('score').desc() ) hiscores = Hiscore.objects.annotate(rank=row_number_rank).filter(username='Bob').values() Unexpectedly, adding this filter step has yielded the following incorrect results: { 'id': 2, 'username': 'Bob', 'score_type': 'wins', 'score': 12, 'rank': 1 } { 'id': 5, 'username': 'Bob', 'score_type': 'kills', 'score': 2, 'rank': 1 } Randomly, … -
How can i display the name of the MenuCard, the MenuCardCategories and the associated MenuCardFood in the .html document with jinja2?
i want to buld a menuCard, with categories and food. It should be possible to create multiple menusCards. #My Try enter image description here How can i display the name of the MenuCard, the MenuCardCategories and the associated MenuCardFood in the .html document with jinja2? The result should look like this... #first menuCard menuCardName menuCardCategoryName foodName foodName foodName menuCardCategoryName foodName foodName foodName #second menuCard menuCardName menuCardCategoryName foodName foodName -
TypeError: 'int' object is not iterable when passing arguments to function
I have a function that does some calculations based on a filtered queryset. I am seeking to pass arguments to the function to inform the filter. The basics: A view to test the output: def TestPlayerData(request): data = PlayerData(1,2) print(data) return HttpResponse(data) The function called is: def PlayerData(game, player): """This is a function based on EventFilterView""" opponent = [2] qs = Event.objects.filter(g_players=player).filter(g_name__in=game).filter(g_players__in=opponent) count_wins = len(qs.filter(g_winner=player)) count_played = len(qs.filter(g_players=player)) if count_played == 0: win_ratio = 'na' else: win_ratio = count_wins/count_played return count_wins, count_played, win_ratio The error received: "TypeError: 'int' object is not iterable" However, if I explicitly name the variables in the function rather than pass them from the view, the function works as expected -- like this: def PlayerData(): """This is a function based on EventFilterView""" game = [1] player =2 opponent = [2] qs = Event.objects.filter(g_players=player).filter(g_name__in=game).filter(g_players__in=opponent) count_wins = len(qs.filter(g_winner=player)) count_played = len(qs.filter(g_players=player)) if count_played == 0: win_ratio = 'na' else: win_ratio = count_wins/count_played return count_wins, count_played, win_ratio I am obviously missing some basic python understanding here and would appreciate a point in the right direction. -
PYTHON- Return minimum three digits
I want to return minium three digits maximum whatever it has it should return. I have tried following function, def get_code(model, prefix): content = model.objects.filter(code__startswith=prefix).last() last = None code_prefix = prefix if content: a_string = content.code split_strings = [] n = len(prefix) for index in range(0, len(a_string), n): split_strings.append(a_string[index: index + n]) last = int(split_strings[1]) if last is not None: suggested = last + 1 else: suggested = 1 return "{}{:03d}".format(code_prefix, suggested) Above code returns threedigits only if i have 4 didits it skips for calculation also. it takes only three digits for calucualtion also. how can i fix this??? -
can't open file '.manage.py': [Errno 2] No such file or directory
im trying to follow this tutorial > https://www.youtube.com/watch?v=JD-age0BPVo&t=793s and I'm getting the following error.. I'm using VSC on mac "" Sourav@Souravs-MBP Settle_Guide % python .\manage.py makemigrations /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file '.manage.py': [Errno 2] No such file or directory Sourav@Souravs-MBP Settle_Guide % "" I made sure that I'm on the ri8 directory while running the code..any suggestion? -
Disable custom action in Django based on some condition ( Value of some field in Model )
Disable custom action in Django based on some condition ( Value of some field in Model) . Created a custom action to publish excel in admin panel . I want to disable the publish action once data is published and status is changed to published ( Status is field in model ) -
Django - How to create groups per tenant?
I have a tenant model like this: class Tenant(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: db_table = "tenants" How do i modify groups field from PermissionsMixin, so that i can have separate groups per tenant. class User(AbstractBaseUser, PermissionsMixin): """ Custom user model that supports email. """ email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=True) tenant = models.ForeignKey( Tenant, on_delete=models.CASCADE, null=True, db_column="tenant_id", blank=True ) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) mobile = PhoneNumberField(null=True) objects = UserManager() USERNAME_FIELD = "email" class Meta: db_table = "users" I want to use django-guardian for object level permissions. Im not sure how modifying the existing Group model will impact the working of that library. -
Display Multiple BlogPosts on Blog(Index)Page
I am trying to have the PostPage and EditorialPage show on the Blog(IndexPage). I know it has something to do with the fact that it's only calling the EditorialPage because of: def get_posts(self): return EditorialPage.objects.descendant_of(self).live().order_by("-post_date") But I don't know how to implement multiple pages. I seriously need help on this one. The code is below: ''' BLOG SECTION ''' class BlogPage(RoutablePageMixin, Page): banner_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) description = models.CharField(max_length=255, blank=True,) content_panels = Page.content_panels + [ ImageChooserPanel("banner_image"), FieldPanel("description", classname="full"), ] # PAGINATOR def get_context(self, request, *args, **kwargs): context = super(BlogPage, self).get_context(request, *args, **kwargs) context['blog_page'] = self # https://docs.djangoproject.com/en/3.1/topics/pagination/#using-paginator-in-a-view-function # Paginate all posts by 2 per page paginator = Paginator(self.posts, 3) # Try to get the ?page=x value page = request.GET.get("page") try: # If the page exists and the ?page=x is an int posts = paginator.page(page) except PageNotAnInteger: # If the ?page=x is not an int; show the first page posts = paginator.page(1) except EmptyPage: posts = paginator.object_list.none() context['posts'] = posts context['authors'] = BlogAuthor.objects.all() # Loop through all Authors of Single Posts return context # PAGINATOR END def get_posts(self): return EditorialPage.objects.descendant_of(self).live().order_by("-post_date") @route(r"^(\d{4})/$") @route(r"^(\d{4})/(\d{2})/$") @route(r"^(\d{4})/(\d{2})/(\d{2})/$") def post_by_date(self, request, year, month=None, day=None, *args, **kwargs): self.filter_type = 'date' self.filter_term = … -
Getting pg_config not found error while using docker-compose build command
I am trying to setup a new django project which has docker compose reuquirement , while setting up the project it is stalling while installing psycopg2 and giving errors , I am using a Macbook Air M1. Is this a docker issue or macbook issue? Attaching error screenshot for more details -
How do I prevent csrftoken error when sending via button with JSON?
I have very little knowledge of JSON and JavaScript yet I can't see what seems to be the problem to my code. I already tried this csrf validation for my reference, yet I still get the csrftoken error. I really need this to work on my Django project so please tell me what seems to be the problem here. app.js onSendButton(chatbox) { var textField = chatbox.querySelector('input'); let text1 = textField.value if (text1 === "") { return; } let msg1 = { name: "User", message: text1 } this.messages.push(msg1); fetch( $SCRIPT_ROOT+'/predict',{ method: 'POST', body: JSON.stringify({ message: text1 }), mode: 'cors', headers: { 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, }) .then(r => r.json()) .then(r => { let msg2 = { name: "Sam", message: r.answer }; this.messages.push(msg2); this.updateChatText(chatbox) textField.value = '' }).catch((error) => { console.error('Error:', error); this.updateChatText(chatbox) textField.value = '' }); } views.py def predict(request): text=request.get_json().get('message') #check if text is valid response=get_response(text) message= {'answer':response} return JsonResponse(message) base.html <body> <div class="container"> <div class="chatbox"> <div class="chatbox__support"> <div class="chatbox__header"> <div class="chatbox__image--header"> <img src="https://img.icons8.com/color/48/000000/circled-user-female-skin-type-5--v1.png" alt="image"> </div> <div class="chatbox__content--header"> <h4 class="chatbox__heading--header">Chat support</h4> <p class="chatbox__description--header">Hi. My name is Sam. How can I help you?</p> </div> </div> <div class="chatbox__messages"> <div></div> </div> <div class="chatbox__footer"> <input type="text" placeholder="Write a message..."> <button class="chatbox__send--footer send__button">Send</button> </div> … -
Pytest: Database access denied while running unit test
When I run my unit test using Django-pytest I keep getting the following error. django.db.utils.OperationalError: (1045, "Access denied for user 'ruach'@'localhost' (using password: YES)"). I am using an sqlite database locally which requires no password and using the decorator @pytest.mark.django_db to allow access to the database so I am unsure what else could be causing this. I have run unit tests successfully in the past in the exact same so I am puzzled as to what is causing test runner to be denied access. -
Django - AWS S3 Bucket - Showing images/css but not javascript/webfont and file uploads
I am making a portfolio website using django. Everything is working well on my local machine. I decided to use AWS S3 buckets to host my static files. After following a few tutorials I was able to make a bucket and link my account over. The issue I have now is that the images and css loads fine on my website, however the webfonts and javascript files seem to not work. I also have a link to download my resume, but that does not work. When clicking on the files it gives me an error of: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Key>resume.pdf</Key> <RequestId>xxx</RequestId> <HostId>xxx</HostId> </Error> Interestingly the url in the browser seems to be attempting to pull from AWS. When I go into the S3 bucket I see all files available. When opening images on my website they are properly pulling from AWS. My CORS is set to: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "POST", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] And settings.py is: AWS_S3_REGION_NAME = 'us-east-2' # Your region … -
Django conversation categories for messages with ManyToMany
I am making a kind of social network in Django. This explains basically what I'm doing: Django - Private messaging conversation view The conversations are exclusively between two people, not more. I have a conversation model because when they to their messages, I want the user to have a list of the other users that they have messages with. Here is the relevant view: def writemessage(request, id): profile = Profile.objects.get(id=id) context = { 'profile': profile, } if request.method == 'POST': sender = request.user receiver = profile.user content = request.POST['content'] timestamp = datetime.now() print(sender, receiver, content, timestamp) record = Message(sender=sender, receiver=receiver, content=content, timestamp=timestamp) record.save() senderprofile = Profile.objects.get(user=sender) receiverprofile = Profile.objects.get(user=receiver) record.conversation.add(senderprofile) record.conversation.add(receiverprofile) print(senderprofile, receiverprofile) return redirect('messagespage') return render(request, 'thecode/writemessage.html', context) Here are my models: from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=60) country = models.CharField(max_length=60) skillstolearn = models.CharField(max_length=200) skillstoteach = models.CharField(max_length=200) description = models.TextField() def __str__(self): return self.user.username class Conversation(models.Model): participants = models.ManyToManyField(User) def __str__(self): return self.participants class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') content = models.TextField() conversation = models.ForeignKey(Conversation, default=None, on_delete=models.CASCADE, null=True) timestamp = models.DateTimeField() def __str__(self): return self.sender.username + ' … -
Django argparse: Unrecognized Arguments --settings?
I've looked at the other SO threads about unrecognized argparse arguments, but none of them seem to match up with my situation. Here's my argparse code, located at apps/create_pdf/management/commands/create_pdf.py: from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'html to pdf for specified website.' def add_arguments(self, parser): print('cp#1') parser = argparse.ArgumentParser(description='html to pdf for specified website') parser.add_argument('-w', '--website', nargs =1, action = 'store', choices = ['SITE_1', 'SITE_2'], default='', help='site to be scraped.') args = parser.parse_args() print(args) breakpoint() def handle(self, *args, **options): print('cp#2') # create_pdf_from_html() I run this from the terminal like so: python3 manage.py create_pdf --website=SITE_1 --settings=server_config.settings ...and I'm getting this error: manage.py: error: unrecognized arguments: create_pdf --settings=server_config.settings The settings path is correct and if I'm not using argparse, everything runs fine. What am I missing? -
Django settings module is defined but still not working
What I am essentially trying to do is generate problems and connect those problems to a model, The generation part worked perfectly but until I tried to update the generated values to a model, I keep getting the error django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I've tried calling settings.configure() in wsgi.py and manage.py but no luck. I already have DJANGO_SETTINGS_MODULE defined in wsgi.py and even in the script, I have it defined as well using. I also tried adding the variable using shell and used Django-admin but still had no luck os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'QuickChemistry.settings') Here is a picture of my project tree: I believe that the error is coming from the actual script itself which was working perfectly before, but when I tried to add it to a model is when this error occurred. This error happens whenever I run django_compounds.py. Here is the django_compounds.py file in a hastebin since it is fairly long https://www.toptal.com/developers/hastebin/umesotedir.py -
I have a trouble using win32com in DJango
I made a python module getting stock infomation and making DataFrame from another window Application by win32com. I can get stock infomation well at first call. but i can't get stock infomation by win32com in succession. and error code is not given. myModule.py import json import pandas as pd import win32com.client import pythoncom def getStock(code, name, startDay): pythoncom.CoInitialize() cpOhlc = win32com.client.Dispatch('CpSysDib.StockChart') today = datetime.today() _startDay = datetime.strptime(startDay, '%Y%m%d') dif = today - _startDay qcy = math.trunc(int(dif.days)) cpOhlc.SetInputVAlue(0, code) cpOhlc.SetInputVAlue(1, ord('2')) cpOhlc.SetInputVAlue(4, qcy) cpOhlc.SetInputVAlue(5, [0,5]) cpOhlc.SetInputVAlue(6, ord('D')) cpOhlc.SetInputVAlue(9, ord('1')) cpOhlc.BlockRequest() count = cpOhlc.GetHeaderValue(3) data = [] date = [] for i in reversed(range(count)): __date = str(cpOhlc.GetDataValue(0,i)) _date = pd.Timestamp( year=int(__date[0:4]), month=int(__date[4:6]), day=int(__date[6:8]) ) date.append(_date) data.append([ cpOhlc.GetDataValue(1,i) ]) df = pd.DataFrame(data, columns=[name], index=date) pythoncom.CoUninitialize() return df -
Why isn't the Google login page rendered properly?
I'm developing a Django application and I tried to implement login with Google account. It works, but I'm not sure why the CSS isn't working when I press the sign up with google button? Screenshot This is the code for the google sign up button: <a class="waves-effect light btn btn-block btn-google" href="{% provider_login_url 'google' %}" style="width: 50%; font-size: small;"> <img src="https://img.icons8.com/color/16/000000/google-logo.png"> Sign up with Google </a> -
Module installed but "ModuleNotFoundError: No module named <module_name>" which running gunicorn
I am trying to deploy this website using nginx. The site is configured correctly and this has been verified when I run python manage.py runserver. But when I run the same using gunicorn and wsgi, gunicorn --bind 0.0.0.0:8002 config.wsgi it lays out error: ModuleNotFoundError: No module named 'crispy_forms'. Crispy_forms are installed and has been verified using pip freeze. Virtual enviornment is also enabled. 'crispy-forms' is also already added in INSTALLED_APPS in settings.py. Following is my error code: root@devvm:/tmp/tmc_site# gunicorn --bind 0.0.0.0:8002 config.wsgi [2022-02-03 23:03:07 +0000] [6333] [INFO] Starting gunicorn 20.1.0 [2022-02-03 23:03:07 +0000] [6333] [INFO] Listening at: http://0.0.0.0:8002 (6333) [2022-02-03 23:03:07 +0000] [6333] [INFO] Using worker: sync [2022-02-03 23:03:07 +0000] [6335] [INFO] Booting worker with pid: 6335 [2022-02-04 04:03:07 +0500] [6335] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.8/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.8/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.8/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.8/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.8/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.8/dist-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Django queryset .iterate(): not working. Only first item is taken into account, second is ignored
I have the following code. I know the queryset contains 2 items. However, Django only creates one entry. What am I overlooking? I know "OrderItem.objects.filter(order=order)" returns two objects. However, in the order_lines.iterate() it only creates one entry. Do I overlook something? order_lines = OrderItem.objects.filter(order=order) inv_ref = (str(order.order_date.year) + "-" + str(10000+order.id)) inv = Invoice.objects.create(invoice_ref=inv_ref,date=order.order_date, order=order, ship_to=order.order_ship_to, bill_to=order.order_bill_to) value = 0 vat = 0 total = 0 commission = 0 ## Looping not working properly: fix all items to be added to invoice. for item in order_lines.iterator(): exvat = (item.price/((100+item.vat)/100)) val = item.quantity * exvat ttl = (item.price*item.quantity) comm = item.commission vat_val = ttl-val InvoiceItems.objects.create(invoice=inv, order_item=item, quantity=item.quantity, price=exvat, value=val, vat=item.vat,vat_val=vat_val,total=ttl) value = value + val vat = vat + vat_val total = total + ttl commission = commission + comm print(item) -
Static File and Media Accessing issue while Deploying Django app in Production Environment
While deploying django app on production environment in openlitespeed server, static files and media files not found. App is woking fine in development environment in local, but after uploading it to server, static content and media files are not accessible. I have updated my static url as follow: STATIC_URL = '/public/static/' STATIC_ROOT = '/home/domain.com/app/public/static Where app is the project location. I am getting 404 for error for all static and media files: Failed to load resource: the server responded with a status of 404 () When I try collectstatic I am getting following error on terminal: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I tried many options, none of the options worked. Any solution will be highly appreciated -
Should .js files be public when serving django files through AWS S3 bucket?
My django collectstatic command uploads fine to AWS S3 bucket, but runs into an 403 error when trying to access static files. From what I've seen from searching around is that my ACL is defaulting to 'private' and I need to change the settings to allow the writer to set ACL to 'public-read'. I've tried messing with the settings to set ACL to 'public-read' and it allows collectstatic and the website to run fine. However, it also allows anyone to inspect element and view my static files. Is having your static files publicly viewable common practice? It seems like it might be a security risk for anyone to be able to read my js files. If there's something I'm missing with my configuration of django please let me know. My settings file: USE_S3 = os.getenv('USE_S3') == 'TRUE' if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')