Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to horizontally space bootstrap form
Here's how my django filter form looks like: I need to horizontally space them a little so that 'Name contains' and the search bar, and 'result' etc are not glued to each other. Here's my html code: <form action="" method="get" class="form-inline text-white justify-content-center mx-3"> {{myfilter.form|bootstrap}} <button class="btn btn-primary" type="submit"> Search</button> </form> I have tried adding m-3, mx-3 etc but they don't work. Little help will be appreciated. Thanks! -
Creating an ecommerce site with Django
I am looking into setting up a box subscription-type business and have chosen Django as my ecommerce platform of choice. At first, I decided to build the back-end from scratch with custom models and such. However, I have since realised it would be much wiser to utilise a framework, to get up-and-running as fast as possible. I have concluded that django-shop would be the best option as it provides the most customisation, at least in my opinion. The problem is that I can't seem to find any resources about implementing it. The documentation provides a cookiecutter template, but I would prefer to build it from scratch and not struggle with changing or removing the aspects I don't want, such as React. If ayone has any resources or tutorials about setting up a custom django-shop app, I would really appreciate it! -
I am trying to display result table but subject1_title, subject1_credit_hour, subject1_grade and subject1_remarks are showing blank in frontend
I have created the models.py with folling value but unable to diplay in frontend. subject1_title=models.CharField(max_length=40) subject1_credit_hour=models.TextField() subject1_grade_point=models.TextField() subject1_grade=models.TextField() subject1_remarks=models.CharField(max_length=20, null=True, blank=True) my home.html page looks like this. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> th, td { border: 2px solid #666; } table.t1 { table-layout: fixed; width: 40%; } </style> </head> <h1><center>Search Your Result</center></h1> <br> <form method="POST" action=" " align="center"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"/> <br> <br> <br> {% for result_query in objects %} <table align="center"> <tr> <th>S.N</th> <th>Course Code No.</th> <th>Course Title</th> <th>Cr.Hr.</th> <th>Grade Point</th> <th>Grade</th> <th>Remarks</th> </tr> <tr> <td>{{ result_query.subject1_code }}</td> <td>{{ result_query.subject1_title }}</td> <td>{{ result_query.subject1_credit_hour }}</td> <td>{{result.query.subject1_grade_point}}</td> <td>{{result.query.subject1_grade}}</td> <td>{{result.query.subject1_remarks}}</td> </tr> <tr> <td>{{ result_query.subject2_code }}</td> <td>{{ result_query.subject2_title }}</td> <td>{{ result_query.subject2_credit_hour }}</td> <td>{{result.query.subject2_grade_point}}</td> <td>{{result.query.subject2_grade}}</td> <td>{{result.query.subject2_remarks}}</td> </tr> <tr> <td>{{ result_query.subject3_code }}</td> <td>{{ result_query.subject3_title }}</td> <td>{{ result_query.subject3_credit_hour }}</td> <td>{{result.query.subject3_grade_point}}</td> <td>{{result.query.subject3_grade}}</td> <td>{{result.query.subject3_remarks}}</td> </tr> <tr> <td>{{ result_query.subject4_code }}</td> <td>{{ result_query.subject4_title }}</td> <td>{{ result_query.subject4_credit_hour }}</td> <td>{{result.query.subject4_grade_point}}</td> <td>{{result.query.subject4_grade}}</td> <td>{{result.query.subject4_remarks}}</td> </tr> <tr> <td>{{ result_query.subject5_code }}</td> <td>{{ result_query.subject5_title }}</td> <td>{{ result_query.subject5_credit_hour }}</td> <td>{{result.query.subject5_grade_point}}</td> <td>{{result.query.subject5_grade}}</td> <td>{{result.query.subject5_remarks}}</td> </tr> <tr> <td>{{ result_query.subject6_code }}</td> <td>{{ result_query.subject6_title }}</td> <td>{{ result_query.subject6_credit_hour }}</td> <td>{{result.query.subject6_grade_point}}</td> <td>{{result.query.subject6_grade}}</td> <td>{{result.query.subject6_remarks}}</td> </tr> </table> {% endfor %} </form> </html> I taking register# and name to search the database result, able to … -
Insert data in postgresql table django
Here is how my views.py looks like @api_view(['GET', 'POST']) def AnswersList(request): if request.method == 'GET': # user requesting data snippets = PAResponse.objects.all() serializer = PAAnswersSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': # user posting data serializer = PAAnswersSerializer(data=request.data) #print("serializer in post",type(serializer),serializer) if serializer.is_valid(): serializer.save() # save to db result=Calculate(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) in post method i am sending my serializer as an argument to the "Calculate" function which is written in calculations.py . Calculate function returns me a list . but i am struggling on how can i send the element of list in different model from calculations.py list looks like this Result_list= [1,20,14,14,38,8,82] which i want to send in AnalysisResult class of model. My models.py class AnalysisResult(models.Model): user_id=models.IntegerField(primary_key=True) E=models.IntegerField() A=models.IntegerField() C=models.IntegerField() N=models.IntegerField() O=models.IntegerField() total=models.IntegerField() class Meta: db_table='analysis_result' def __str__(self): return self.response Please let me know if you need any more information. i am new to this so please help me . In simple terms can i send "Result_list" to db_table='analysis_result' directly from calculations.py instead of views or models.py if not then how can i send data . Any kind of lead will be helpful DB=postgressql 13 -
access field of foregin key in django model function
Let's say I have the following models.py: from django.db import models class Person(models.Model): name = models.CharField(max_length=100) father = models.ForeignKey(Person, on_delete=models.CASCADE) And I need to add a function fullName(self) that will return a string, the person's name + space + the person's father name. What is the correct syntax to do this? I tried the following but it doesn't work from django.db import models class Person(models.Model): name = models.CharField(max_length=100) father = models.ForeignKey(Person, on_delete=models.CASCADE) def fullName(self): return self.name + " " + self.father.name pylint says: instance of 'ForeginKey' has no 'name' member -
Django data save model without form in template
I want to save a value in the database when the button is clicked without using a form. I want to save the value in h2 to another model when the button is clicked. What can i do? TEMPLATE <div class="widget-main"> <center><h2 name="urun" value="{{ urun.urun_adi }} ">{{ urun.urun_adi }}</h2></center> </a> <input type="submit" data-actions-icnt="sepete_ekle/" value = "sepete ekle" class="btn btn-sm btn-default pull-right"> Sepete Ekle </inputa> <a href="" class="btn btn-sm btn-success">{{urun.fiyat}} TL</a> </div> VIEWS def sepete_ekle(request): if request.method == 'POST': urun = request.POST["urun"] status = 0 urunler = Siparis.objects.create(urun,status) urunler.save() messages.success(request, " Sepete Eklendi") return redirect('/bayi/profil_duzenle') else: return HttpResponseRedirect("/") MODEL class Siparis(models.Model): bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"}) urun = models.ForeignKey(Urun, on_delete=models.CASCADE) adet = models.IntegerField() tarih = models.DateTimeField() status = models.BooleanField() class Meta: verbose_name = 'Bayi Sipariş' verbose_name_plural = 'Bayi Siparişleri' -
can I send email once at a particular time using celery?
I am sending emails using Amazon SES using Django. but I want to know if I can send an email to the clients subscribed only once at a particular time. I think using Celery may be possible but I can't implement it. Please give me a solution. Thanks in advance. -
can we create separate view files in django app?
In my django app, i have user,employee,admin modules. do I can create seperate views.py files for user,employee and admin eg: i have folder called "AdminFolder" and I have added seperate adminView.py in it is it allowed in django? -
load templates from database in dajngo
I am working on a project where some templates are stored as part of a 'theme' in the database. Because of this, I'm not able to leverage a lot of Django's nice template rendering functionality immediately, i tried using dajngo-dbtemplates and added template to database but i couldn't find a way how to render those templates to let users to select their choice of template.basically i am working on a project for digitcards that let user to choose their choice of template and shows their details onto it -
django filter using ajax
I use django-filter to sort products. When I use ajax for this, after selecting the category, the sorting operation is not done properly and it query again for all the products and returns the results if it should be only on the products related to the same category that I selected do this. This is done correctly without using ajax. When I am not using ajax, after filtering the products, the url is as follows: category/shoes/10/?brand=4/ But when I use ajax after filtering the url products as follows: /category/shoes/10/ ( I use django-filter to sort products. When I use ajax for this, after selecting the category, the sorting operation is not done properly and it query again for all the products and returns the results if it should be only on the products related to the same category that I selected do this. This is done correctly without using ajax. When I am not using ajax, after filtering the products, the url is as follows: category/shoes/10/?brand=4/ But when I use ajax after filtering the url products as follows: /category/shoes/10/) filter.py: class ProductFilter(django_filters.FilterSet): brand = django_filters.ModelMultipleChoiceFilter(queryset=Brand.objects.all(), widget=forms.CheckboxSelectMultiple) url: path('filter/', views.product_filter, name='filter') views: def product_filter(request, slug=None, id=None): products = Product.objects.all() category = … -
How can I use email scheduling same as Gmail using Django?
Hii All I have a question as we all know that Gmail has a new feature of scheduling email on a given date and time. I am also trying to build the same feature for my project. And all I have completed, the dashboard, users email and everything. Can Anyone suggest me step by step guide to build this feature. Thanks in advance. For the information I am trying to build with django-post_office library, I also tried RabbitMq message broker and celery but I am unable to find a way. I want somthing like this no other changes Captcha Meaning -
Please anyone help me I'm getting IntegrityError at /cart/ in django ecommerce Duplicate entry
Please somebody help me I'm stuck here and don't know why I'm getting this error. I'm trying to build an e-commerce website and when I try to add a customer to the cart through Mixin I get this error. This is my models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=70) middle_name = models.CharField(max_length=70) last_name = models.CharField(max_length=70) email = models.EmailField(unique=True) mobile = PhoneField(unique=True) registered_date = models.DateTimeField(auto_now_add=True) def __str__(self): full_name = self.first_name + ' ' + self.middle_name + ' ' + self.last_name return full_name class Meta: ordering = ['first_name'] class Cart(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, unique=False, null=True, blank=True) total = models.PositiveIntegerField(default=0) def __str__(self): return 'Cart:' + str(self.id) class CartProduct(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.CharField(max_length=100, blank=True, null=True) rate = models.PositiveIntegerField() quantity = models.PositiveIntegerField() subtotal = models.PositiveIntegerField() def __str__(self): return 'Cart:' + str(self.cart.id) + 'CartProduct:' + str(self.id) this is my views.py class CustomerToCartMixin(object): def dispatch(self, request, *args, **kwargs): cart_id = request.session.get('cart_id') if cart_id: cart_obj = Cart.objects.get(id=cart_id) if request.user.is_authenticated and request.user.customer: cart_obj.customer = request.user.customer cart_obj.save() else: pass return super(CustomerToCartMixin, self).dispatch(request, *args, **kwargs) class CartView(CustomerToCartMixin, generic.TemplateView): template_name = 'accounts/cart.html' def get_context_data(self, **kwargs): context = super(CartView, self).get_context_data() cart_id = self.request.session.get('cart_id', None) if cart_id: cart_obj = Cart.objects.get(id=cart_id) else: cart_obj = … -
How to add cores headers in Django ajax call
I tried to hit the API using an ajax call. but it's throwing this Error (from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request). I add cores headers settings in Django settings and headers also added in ajax call. but I could not get the data throwing the same error. Ajax Code $.ajax({ url: "{{ api.endpoint }}", type: "GET", beforeSend: function(request) { request.setRequestHeader("Access-Control-Allow-Origin", 'http://127.0.0.1:8000'); }, data: { "limit" : 1, "api_key" : "{{ api.token }}" }, success: function(data) { alert("Your Connection is successful. Retrieved " + data.length + " records from the dataset!"); }, error: function(err) { console.log(err) alert("Connection Failed."); } }); -
why the django admin console is terminating the web server automatically?
I have created a custom User model as I wanted to use email as unique constraint. Below is the code snippet models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, shop_name, contact, password, **extra_fields): values = [email, contact] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, contact=contact, shop_name=shop_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, shop_name, contact, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, shop_name, contact, password, **extra_fields) def create_superuser(self, email, shop_name, contact, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, shop_name, contact, password, **extra_fields) class Shop(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) shop_name = models.CharField(max_length=150) contact = models.CharField(max_length=10) State = models.CharField(max_length=100) district = models.CharField(max_length=100) location = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(null=True) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['shop_name', 'contact', 'State', 'district', 'location', 'is_staff'] def get_full_name(self): return self.shop_name def get_short_name(self): return self.shop_name.split()[0] class Medicine(models.Model): medicine_name = models.ForeignKey(Shop, on_delete=models.CASCADE, … -
Theme Choosing Option for a Django Project not working properly
Helloo, I am following a tutorial to allow User to select Light/Dark Mode using HTML, CSS, JS. I have following documentation and tutorial but the issue is that the content of the page itself is not showing and I am not sure the reason. So what I did is I created 2 css files dark and light, and create a mode application with the settings. I am currently receiving an error: django.contrib.auth.models.User.setting.RelatedObjectDoesNotExist: User has no setting. To start here is the base.html <link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet"> <!-- Mode --> <div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right"> <button onclick="swapStyle('css/app-light.css')" type="button" class="btn btn-secondary">Light Mode</button> <button onclick="swapStyle('css/app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button> </div> <!-- Mode --> <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); var cssFile = "{% static 'css' %}" function swapStyles(sheet){ document.getElementById('mystylesheet').href = cssFile … -
Can't get kwargs data in function in Django Celery Beat
I'm implementing a reminder module in the application using Django celery-beat, I'm creating cron tab in periodic tasks and passing dictionary in kwargs parameter. It's successfully saved in Django periodic task table but when the scheduled task runs on time and calls the mentioned function, it's not getting kwargs data and through the exception. settings.py INSTALLED_APPS = [ 'django_celery_beat', ] # CELERY STUFF CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "redis://localhost:6379" CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' init.py from .celery import app as celery_app all = ("celery_app",) celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings_local") app = Celery("baseapp") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() Here is the task scheduler function which is creating periodic tasks: def task_scheduler(raw_data): try: if raw_data["start"] and raw_data["reminder"]: reminder_time = datetime.datetime.strptime(raw_data["start"], '%Y-%m-%dT%H:%M:%S.%fZ') - datetime.timedelta(minutes=raw_data["reminder"]) reminder, _ = CrontabSchedule.objects.get_or_create( minute=reminder_time.minute, hour=reminder_time.hour, day_of_week="*", day_of_month=reminder_time.day, month_of_year=reminder_time.month, ) PeriodicTask.objects.update_or_create( name=raw_data["summary"], task="reminder_notification", crontab=reminder, expire_seconds=7200, kwargs=json.dumps({'test111':'123'}), ) except Exception as error: print(error) Here is a reminder notification function which is called when the task runs on time: @shared_task(name="reminder_notification") def reminder_notification(*args, **kwargs): print("hello task") Here are tasks in the database: Here is the error: What am I doing wrong? -
What does "django.db.utils.ProgrammingError: relation "silk_request" does not exist LINE 1: INSERT INTO "silk_reque mean?
So, here is what I have done. I have cloned this repo https://github.com/hitul007/complianceok followed by git stash then git checkout due_date and git pull origin due_date when i tried to run the server, it throws an error which i couldnt understand. Not only that, I could not even locate the file where this actual problem is? What is this silk thing? Can someone please explain what is the actual issue and how do I solve it? I am using python 3.8 and django 3.1.2enter image description here Thank you very much -
Styling Email with inlinecss
I am looking to send email after a form is validated in Django. The email works well, except that it is delivered with no CSS formating. I was told to add the following to the template: {% load inlinecss %} {% inlinecss "css/MegaTemplate-dashboard.css" %} Code... {% endinlinecss %} My set up is as follow NewAlgo > Core > Static > assers > css > MegaTemplate-dashboard.css In my settings.py I have : # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) When I submit the form, everything goes well until the mailing section, and I get the error : FileNotFoundError at /restrictedname/new/ [Errno 2] No such file or directory: 'P:\\NewAlgo \\staticfiles\\css\\MegaTemplate-dashboard.css' Does anybody knows what I am not doing right please ? -
Django contact page without sendgrid
I have a working django contact page, currently configured to send the mail message to the console, as well as tested with my server. The only issue with using my server settings, is that it uses the pre-configured email in my settings.py to send the message. And I'd like custom email addresses to be entered. I've seen sendgrid is one way of doing this, but I'd like to know if I can achieve this without using a service like sendgrid? -
how to sum the two definition functon value in django
how can i sum these two Hbase user and Hbase system in one def function? I wan t do like this but now i have no idea how to continue... def HbaseStagingCpuUser(self): request = self.request self.request.set_MetricName('cpu_user') responseCpuUsed = response_dict['Datapoints'] cpu_user_data = json.loads(responseCpuUsed) cpu_user_list = [] for user_data in cpu_user_data: cpu_user_dict = { 'host': user_data['host'], 'value': user_data['Average'], 'timestamp': math.trunc(datetime.fromtimestamp(user_data['timestamp']/1000.0).replace(second=0, microsecond=0).timestamp()) } cpu_user_list.append(cpu_user_dict) #print(cpu_user_list) return cpu_user_list def HbaseStagingCpuSystem(self): request = self.request request.set_MetricName('cpu_system') cpu_system_list = [] cpu_system_data = json.loads(responseCpuSystem) for system_data in cpu_system_data: cpu_system_dict = { 'host':system_data['host'], 'value':system_data['Average'], 'timestamp': math.trunc(datetime.fromtimestamp(system_data['timestamp']/1000.0).replace(second=0, microsecond=0).timestamp()) } cpu_system_list.append(cpu_system_dict) #print(cpu_system_list) return cpu_system_list sum def SumHbaseCpu(HbaseStagingCpuUser,HbaseStagingCpuSystem): -
how to store a dictionary in a djongo model?
I need to store daily values of date and price for many stocks. I get this data in the next format: {"stockname":"XXX","currency":" ","values":[["2021-01-06","1.00"]]} Im using Djongo to store the data, however, i don't know what kind of Field i should use to store the dictionary in my app. My goal is to add the latest date and price of a stock daily. My idea was to have each document with the next structure: {"stockname":"NAME","FirmName":"Firm","DailyValues":[["2020-01-01","1.00"],...,["2020-01-06","2.00"]]} But im not sure if a list of lists is supported for a django model. Thank you in advance. -
Django 404 Email spam
I recently launched a web application based Django, and have been very pleased with its results. I also turned on a feature in Django where you can have emails sent to MANAGERS for 404's by adding the middleware 'django.middleware.common.BrokenLinkEmailsMiddleware'. However, ever since I did that, I'm getting LOTS of spam requests hitting 404s. I'm not sure if they are bots or what but this is the information I'm getting from Django: Referrer: http://34.212.239.19/index.php Requested URL: /index.php User agent: Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6) IP address: 172.31.23.16 Why am I getting requests to URL's that don't exist on my site and is there a way to filter out requests so I don't get emails for them? These URL's have never existed on my site (my site is very recently launched). I'm getting roughly 50-100 emails a day from spam requests to my site. Any help is appreciated! -
How to add multiple ckeditor in django template for same model field?
I have Multiple Choice Question model and answer model. For one question there are 4 answers. I need to add ckeditor in all 5 field. No problem with question field, but i can not get it work for 4 answer fields. I tried replace textarea with ckeditor but can not get image upload to work. -
The included URLconf 'myapp.urls' does not appear to have any patterns in it
I have an interesting issue.. hope you have seen this kind of behavior. I have django 3.1.4 and running on python 3.6.2. The project I am working on works fine, i can access all the urls and the endpoints function like they way they should. While working on the code, when I make a mistake in one of the classmethod of a class and try to run django, python manage.py runserver localhost:4444, I get this error, 'The included URL.conf 'myapp.urls' does not appear to have any patterns in it.` I know that I didnt touch the urls file and everything is how it should be (besides the error in my classmethod). If I run, python manage.py makemigrations, only then can i see the actual error that needs to be resolved. Otherwise, only error that django throws when running the runserver is the URL.conf error. Besides the imports, I only have this block in my myapp.urls. I need these for the @api_views that I have in my views.py file. urlpatterns = [ url('admin/', admin.site.urls), url('api/', include('other.urls')), url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), ] Anything I need to configure or is it by design? If you need more information, happy to provide that. -
How do I store environment variables both locally and not to have to change code when deploying on Heroku in Django
I have a Django project I have been working on offline and now I have hosted it on Heroku and it works well on Heroku but fails on my local machine with this error. File "/usr/lib/python3.9/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DEBUG' and I think it is because I used environment variables like this. from boto.s3.connection import S3Connection import os DEBUG = S3Connection(os.environ['DEBUG'], os.environ['DEBUG']) I also have a .env file in my root(project folder) with the environment variables like this. export JWT_SECRET_KEY = "dfge..." export DEBUG = 1 What is the right way to store the environment variables on my local machine?