Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model with @classmethod testing
I have some problem with my model testing. I have model . > class Reminder(models.Model): > STATUS = ( > (1, 'Active'), > (2, 'Archived'), > (3, 'Deleted'), > ) > user = models.ForeignKey(User, on_delete=models.CASCADE) > title = models.CharField(max_length=64, blank=False) > text = models.CharField(max_length=256) > date_create = models.DateTimeField(auto_now_add=True, verbose_name="Reminder was created") > date_start = models.DateField() > date_finish = models.DateField() > time_reminder = models.TimeField() > day_of_week = models.ManyToManyField(DayOfWeek) > status = models.IntegerField(choices=STATUS, default=1) def __str__(self): return r'{} --> {}'.format(self.title, dict(self.STATUS).get(self.status)) @classmethod def from_db(cls, db, field_names, values): instance = super().from_db(db, field_names, values) instance._loaded_values = dict(zip(field_names, values)) return instance def clean(self): super(Reminder, self).clean() start = self.date_start finish = self.date_finish now = datetime.datetime.now().date() if not self._state.adding: if self._loaded_values['status'] == 2 and self.status == 1: if start < now: raise ValidationError('Updating: Date start has to be grater current date.') Everything works fine but tests. def test_Model_test_create_rem_start_gt_now(self): reminder2 = Reminder.objects.create( user=self.user, title='title2', text='text2', date_start=datetime.datetime.strptime('18 Sep 2020', '%d %b %Y'), date_finish=datetime.datetime.strptime('19 Sep 2021', '%d %b %Y'), time_reminder=self.time ) reminder2.refresh_from_db() # tried this try: reminder2.full_clean() except ValidationError as err: self.assertEqual(err.messages[0], ' ') I have error ERROR: test_Model_test_create_rem_start_gt_now (myrem.tests.ReminderTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/cat/ProjectsGit/ProjectReminder/Reminder/myrem/tests.py", line 71, in test_Model_test_create_rem_start_gt_now reminder2.full_clean() File "/home/cat/ProjectsGit/NewReminder/venv/lib/python3.8/site-packages/django/db/models/base.py", line 1216, in full_clean self.clean() … -
Django not loading style file from static directry
I am facing a strange issue with the Django application on my local, the file is available in the static directory. The following is in the settings.py STATIC_ROOT = SITE_ROOT + '/static/' STATIC_URL = '/static/' this is how I am trying to include style file <link href="/static/msc.css?v=1.2" rel="stylesheet" type="text/css" /> the following is added in urls.py from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() The file exist in the static directory, but it is not loading, I am facing a 404 error in console for the URL: http://localhost:8000/static/msc.css?v=1.2 please help me in this regard thanks. -
I want to use jQuery, popover and BootStrap 5 in my project what should be the correct sequence here?
I am using BootStrap version 5.0.0 beta-2, I'm trying to add button dynamically in my popover which I can't. I've included scripts in the following order: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script> My code to update popover is like this: // Updating Popover function updatePopover(cart) { popStr = ""; i = 1; popStr = popStr + "<div class='my-2 mx-1'>"; for (item in cart) { popStr = popStr + "<b>" + i + ". </b>"; popStr = popStr + document.getElementById('name' + item).innerHTML + " | <b>Qty:</b> " + cart[item] + "<br>"; i += 1; } // Adding Clear Cart and Checkout buttons popStr = popStr + "</div> <a href='/shop/checkout'><button class='btn btn-primary' id='checkout'>Checkout</button></a> <button class='btn btn-primary' id='clearCart' onclick='clearCart();'>Clear Cart</button>"; console.log(popStr); // Getting popcart by ID var popcart = document.getElementById('popcart') // Enabling popover var popover = new bootstrap.Popover(popcart, 'data-bs-content') // Setting new value of popcart popcart.setAttribute('data-bs-content', popStr); // Showing the popover popover.show(); } My HTML division is like this: {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem; border: 0px;"> <img src="/media/{{i.product_img}}" class="card-img-top" alt="{{i.product_name}}"> <div class="card-body text-center"> <h6 class="card-title" id="namepid{{i.id}}">{{i.product_name}}</h6> <p class="card-text">{{i.product_desc|slice:":25"}}{% if i.product_desc|length > 25 %}...{% endif %}</p> <span id="divpid{{i.id}}" class="divpid"> <button … -
Display user by filtering database in Django
I have two types of users in my model. And I am trying to get only one type of user to display on my HTML page. I am new to Django, so I am having some small problems. And place try to explain in a comment This is my models.py file: class CustomKorisnici(AbstractUser): MAJSTOR = '1' KORISNIK = '2' USER_TYPE_CHOICE = ( (MAJSTOR, 'majstor'), (KORISNIK, 'korisnik') ) user_type = models.CharField(max_length=100,blank=True,choices=USER_TYPE_CHOICE) username = models.CharField(max_length=100,unique=True) last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) profile_image = models.ImageField(null=True, upload_to="images/", default='korisnici/static/post_user/images/profile_image.png') is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=100,unique=True) bio = models.TextField(default=" ") After this a setup my view.py file for filtering data from the database: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, TaskCategory,CustomKorisnici from .forms import PostForm, updatePost from django.urls import reverse_lazy,reverse from django.http import HttpResponseRedirect class MajstoriView(ListView): model = CustomKorisnici context_object_name = 'majstori' template_name = 'majstori_view.html' # html stranica na kojoj ce podaci biti prikazani def get_queryset(self): # get_queryset biblioteka iz paythona return CustomKorisnici.objects.filter(user_type="MAJSTORI") A setup URL after that: from django.urls import path from . import views from .views import MajstoriView urlpatterns = [ … -
Setting up site-specific static folders with Django Sites
I am using Django Sites. I want to be able to have site-specific templates and static files. My current directory structure is: ├── site_a │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── site_b │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── templates ├── site_a │ ├── _navbar.html │ ├── home.html │ └── signup.html └── site_b ├── _navbar.html ├── home.html └── signup.html I know that I can move templates inside the site_x directory if I declare it as an app in INSTALLED_APPS. Is there another way to tell Django to use templates in site_a/templates without declaring site_a as an app? Also, I would also like to have site specific static files that are not placed in the project STATIC_ROOT so that my tree actually looks like: . ├── site_a │ ├── __init__.py │ ├── settings.py │ ├── static │ │ ├── css │ │ └── js │ ├── templates │ │ ├── _navbar.html │ │ └── home.html │ ├── urls.py │ ├── views.py │ └── wsgi.py └── site_b ├── __init__.py ├── settings.py ├── static │ ├── css │ └── js ├── templates │ ├── _navbar.html … -
django "ATOMIC_REQUESTS" 'Lost connection to MySQL server during query'
I found a strange phenomenon. When I added ATOMIC_REQUESTS:True to the database in the settings, django crashed when connecting to MySql. It kept prompting "Lost connection to MySQL server during query". Change ATOMIC_REQUESTS to False and it can be used normally. Someone Encountered similar problems? Djano 3.1 Mysql 5.7 centos6.9 -
Django how to conditionally update of field value based on other field value in a different model?
class Details(models.Model): name = models.CharField(max_length=60) group = models.CharField(max_length=60, choices = TopicCategory.choices) class ChoiceOptions(models.TextChoices): YES = 'YES', _('Yes') NO = 'NO', _('No') NA = 'NA', _('Na') class MakeAChoice(models.Model): myChoice = models.CharField(max_length=60, choices = ChoiceOptions.choices) class DetailsSerializer(serializers.ModelSerializer): class Meta: model = Details fields = ('name','group') class MakeAChoiceSerializer(serializers.ModelSerializer): class Meta: model = MakeAChoice fields = ('mychoice') Here are my models & serializers for the MakeAChoice and Details class. At present, I can make a choice and it gets saved when I fire a POST call. However, I want save my choice only if the value of the 'group' filed is 'Valid'. How do I write the condition for this please? I need to get the field value in the other Model and verify it against a value and only if the condition is true, I want to update the choice in the current model. -
Why the settings module needs a base.py file?
I changed the django configuration file path, and the error is as follows: ModuleNotFoundError: No module named 'app.settings.base'; 'app.settings' is not a package I know it needs a base.py file, why it doesn't work with __init__.py? it's a package with __init__.py -
Django- CSS is not working for other pages such as header tags
I have linked my css file in 'main/static/css/style.css' and my pages are in 'main/templates/main/pages.html'. But the CSS is not working for some pages such as the h2 tag is not taking the style. base.html {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> privacy.html {% extends 'main/base.html' %} {% block content %} <div class="main"> <h1><b>Privacy</b></h1> <div style="height:35px" aria-hidden="true"></div> <div class="text_para"> <h2 class="h2_privacy">Mission</h2> <p>paragraph<p> ....... style.css .main { -ms-flex: 70%; /* IE10 */ flex: 70%; background-color: white; padding: 20px; } .text_para { margin-right: 5%; text-align: justify; } /*heading h2 for privacy page*/ .h2_privacy { color: black; font-family: 'Lucida Calligraphy', sans-serif; } -
Unable to display images inline using Django templates
I am trying to display images inline into mails with Django but it does not work. Here is the line that I use to display the images inline : <img src='http://localhost:8000/static/myproject/media/mypic.jpg' width="125" height="120" style="display: block; border: 0px;" /> I got nothing actually.... Could you help me please ? Thank you very much ! -
pytest-django: Mock settings.DEBUG
To make manual testing easy, I want to create users when the login page gets shown. class LalaLoginView(LoginView): def get(self, request, *args, **kwargs): self.create_users() return super().get(request, *args, **kwargs) @classmethod def create_users(cls): if not settings.DEBUG: return admin = User.objects.update_or_create(username='admin', defaults=dict( is_superuser=True, is_staff=True))[0] admin.set_password('admin') admin.save() My Test: @pytest.mark.django_db def test_create_users_prod(settings): settings.DEBUG=False LalaLoginView.create_users() assert not User.objects.all().exists() But the mocking of settings.DEBUG does not work. In create_users() DEBUG is "True". How to mock settings.DEBUG with pytest-django? -
Docker-compose build error with django and mysql
I trying to build a Django project with docker-compose and MySQL, but when i run the "docker db uses an image, skipping Building with native build. Learn about native build in Compose here: Building web Sending build context to Docker daemon 22.02kB Step 6/6 : COPY . /code/ ---> 2f42d48fb668 Successfully built 2f42d48fb668 Successfully tagged djangonew_web:latest Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose/cli/main.py", line 80, in main File "compose/cli/main.py", line 192, in perform_command File "compose/metrics/decorator.py", line 18, in wrapper File "compose/cli/main.py", line 369, in build File "compose/project.py", line 521, in build File "compose/project.py", line 503, in build_service File "compose/service.py", line 1131, in build File "compose/progress_stream.py", line 22, in stream_output File "compose/utils.py", line 50, in split_buffer File "compose/utils.py", line 26, in stream_as_text File "compose/service.py", line 1894, in build FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpjwyh07ql' [16684] Failed to execute script docker-compose My Dockerfile: FROM python:3 ENV PYTHONBUFFERD=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ My docker-compose.yml file: version: "3.9" services: db: image: mysql environment: - MYSQL_DB=mysql_test - MYSQL_USER=test - MYSQL_PASSWORD=test - MYSQL_ROOT_PASSWORD=test web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: … -
Configuring django-cachealot with django_tenants
Trying to use django-cachealot with django_tenants. I get the following error right at the start. Anyone got a resolution? (cachalot.W003) Database engine 'django_tenants.postgresql_backend' is not supported by django-cachalot. HINT: Switch to a supported database engine. -
Is there a way to avoid patching IPython embed when patching sockets?
In my Django test suite, I typically use from IPython import embed; embed() in a test to debug when working locally. I have a mixin class that I use to patch all socket connections to avoid outgoing API calls as such: class ServicesTestMixin(object): @classmethod def setUpClass(cls): # Patch all network known issues mock_obj = patch('socket.socket.connect').start() mock_obj.side_effect = Exception('TESTS TRIED TO ACCESS SOCKET NETWORK!') mock_obj = patch('socket.socket').start() mock_obj.side_effect = Exception('TESTS TRIED TO ACCESS SOCKET NETWORK!') return super().setUpClass() I use it like this: from django.test.testcases import TestCase class MyTestCase(ServicesTestMixin, TestCase): def test_example(self): hello = True from IPython import embed; embed() self.assertTrue(hello) The issue is that now when I call from IPython import embed; embed() in a test the exception is raised because embed() is opening up a socket connection. Is there a way to circumvent or workaround this? Perhaps a way to monkey patch all connections except this embed one? -
Displaying get_context_data in template Django
I am trying to display the get_context_data on the template. I have a method on the model class that I need to call from ProfileView which has two different models. For the Profile View I have Profile Model and for the shippingaddress view I have ShippingAddress Model. And these models are from two different app. I tried the function below and it does not show any error, but when I tried to call it in the Template, It does not show the method. Views.py class ProfileView(LoginRequiredMixin, DetailView): model = Profile template_name = "account/profile.html" success_url = "/" def get_context_data(self, *args, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) context['shipping'] = ShippingAddress.objects.filter(user=self.request.user) return context Template code {{object.get_full_address}} Models.py class ShippingAddress(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone_number = PhoneNumberField(null=True, blank=True) street_address = models.CharField(max_length=300) province = models.CharField(max_length=300) city = models.CharField(max_length=50) country = models.CharField(max_length=50) zip_code = models.CharField(max_length=10) def __str__(self): return str(self.user) def get_phone_number(self): return self.phone_number @property def get_full_address(self): return f"{self.street_address}, {self.province}, {self.city}, {self.country}, {self.zip_code}" -
Cannot assign "<VendorupdateForm bound=True, valid=True, fields=(username;email)>": "VendorImage.vendor" must be a "Vendor" instance
i was trying to upload the multiple images using formset in django while updating the vendor profile but stuck at the above error from few days vendor.py : from django.db import models from .vendorcategory import Vendorcategory from .city import City from django.contrib.auth.models import User from PIL import Image class Vendor(models.Model): name = models.CharField(max_length=150, default="") user = models.OneToOneField(User, on_delete=models.CASCADE, default=1) # city = models.CharField(max_length=50) # vendorcategory= models.CharField(max_length=50) city= models.ForeignKey(City, on_delete=models.CASCADE, default=1) vendorcategory= models.ForeignKey(Vendorcategory, on_delete=models.CASCADE, default=1) state = models.CharField(max_length=50, default="") address = models.CharField(max_length=250, default="") desc= models.CharField(max_length=1150, default='') details= models.CharField(max_length=1150, default="") reviews= models.CharField(max_length=150, default="") phone= models.IntegerField( default="1111111111") pincode = models.IntegerField( default="1111111111") website = models.CharField( max_length=50, default="") email = models.EmailField(max_length=254, default="") facebooklink= models.CharField(max_length=150, default="") instalink = models.CharField(max_length=150, default="") twitterlink = models.CharField(max_length=150, default="") pinterest = models.CharField(max_length=150, default="") images = models.ImageField(upload_to= 'uploads/vendor/', default='uploads/vendor/default.jpg' ) # for uploading multiple images # images = models.FileField(blank=True) location = models.TextField(default='') vendoremail = models.EmailField(default='') vendorpassword = models.CharField(max_length=50, default='') vendorphone = models.CharField(max_length=13, default='') views = models.IntegerField(default=0) @staticmethod def get_all_vendors(): return Vendor.objects.all() @staticmethod def get_all_vendors_by_vendorcategoryid(vendorcategory_id): return Vendor.objects.filter(vendorcategory= vendorcategory_id) def register(self): self.save() def isExists(self): if Vendor.objects.filter(vendoremail = self.vendoremail): return True return False @staticmethod def get_vendor_by_email(vendoremail): try: return Vendor.objects.get(vendoremail=vendoremail) except: return False class VendorImage(models.Model): images1 = models.ImageField(upload_to='uploads/vendor/', default='uploads/vendor/default.jpg') vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, related_name="images1") forms.py : … -
What hosting service should I choose for course website?
I am going to develop the backend for a website that are going to contain videos for our members to watch. We will produce about 50 videos and based on our assessments, we will end up with approximately 5000-10000 members. Does anyone know where and how to host the videos to make it as cheap as possible? (direct link to youtube, and vimeo is not an option). We are using django for backend and postgreSQL database. I tried to use this calculator https://calculator.s3.amazonaws.com/index.html for AWS, but it showed that it will cost us 6000$/month if the videos is 300 MB each. -
Django: How do I allow views and methods with AllowAny permission to bypass authentication with HttpOnly JWT token cookies?
I have applied JWT authentication with HttpOnly cookies using a custom middleware. Now, the middleware checks for the presence of access and refresh tokens as HttpOnly cookies in every request. Everything works well. But, it retuns 'KeyError': 'access' if I request for a page that does not require authentication, say, the homepage or bloglist or blogdetail page. How do I remove this need for access token in these views with permissions set to AllowAny and also in some views where only the GET method permission is set to AllowAny? My view: class TagView(viewsets.ModelViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer def get_permissions(self): if self.request.method == 'PUT': self.permission_classes = [permissions.IsAuthenticated,] elif self.request.method == 'GET': self.permission_classes = [permissions.AllowAny,] elif self.request.method == 'POST': self.permission_classes = [permissions.IsAuthenticated,] return super(TagView, self).get_permissions() If request method is GET, the middleware should pass the request even if no access cookie is found. Now, it checks for the access cookie in every request. I added a line to skip asking for tokens if the request method is GET and if there is no cookie in the request, to mark it as AllowAny view, but I think it is unsafe. My middleware: class AuthorizationHeaderMiddleware: def __init__(self, get_response=None): self.get_response = get_response def … -
Django Generic View (Search and Post Form)
How to Search an athlete and then post a payment in Django Generic View How should I find an athlete in form and then post a payment for the current athlete. Anyone can help me it will be apreciat... I tried this code it finds the athlete but I don't know how to implement the form with it.. views.py class SearchResultsListView(ListView): model = Athlete context_object_name = 'athlete_list' template_name = 'athletes/add-fee.html' def get_queryset(self): # new query = self.request.GET.get('q', None) return Athlete.objects.filter( Q(membership_num__iexact=query) ) code for post the payment ?? This is the template (it is static rightnow) -
Migrate from standard User to Abstract user in Django
I have created a Django Project using the standard User-form. I really need to make use of the email as login (using this guide). The problem is it should be difficult to migrate when I already have used the standard User-form. Since we are only in the testing stage at the moment, I don't mind wiping the entire database to make this migration. Having that in mind, that losing data is not an issue, is there a way to make this migration? -
Post returns 1364, Field 'ADD' doesn't have a default value
THe error upon clicking the POST button on Djangorest Form The serializer: class CreatePolicyBenefitsSerializer(serializers.ModelSerializer): class Meta: model = Policy fields = ('company','name','benefits','price') The views: class CreatePolicyBenefits(CreateAPIView): queryset = Policy.objects.all() serializer_class = CreatePolicyBenefitsSerializer Here the form Is it possible when I hit POST button, the data can be displayed on the form? Thanks -
jQuery not finding class after AJAX response
I have essentially a cart section where a user should be able to remove items from the cart and then the contents are refreshed with AJAX. However, after a cart item is removed the response changes from asynchronous to synchronous and I can't establish why. Sorry new to programming so a lot of things may not be the best way to do something, any help appreciated! Views.py def checkout_detail_api_view(request): customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.cartItems_set.all() '# create lists for items to be put in dictionary' productId_list = [] product_url = [] productName_list = [] location_list = [] img_list = [] checkoutList = {} for item in items: '# append into lists' productId_list.append(item.product_id) productName_list.append(item.product.title) product_url.append(item.product.get_absolute_url()) img_list.append(item.product.image.url) location_list.append(item.product.location) checkoutList["id"] = productId_list checkoutList["title"] = productName_list checkoutList["location"] = location_list checkoutList["image"] = img_list checkoutList["url"] = product_url checkout_data = {"checkoutList": checkoutList} return JsonResponse(checkout_data) def cart_update(request): product_id = request.POST.get('product_id') customer = request.user.customer if product_id is not None: try: product_title = Product.objects.get(id=product_id) except BlogPost.DoesNotExist: print("Show message to user, product is gone?") '# gets or makes product order' order, created = Order.objects.get_or_create(customer=customer, complete=False) '# gets or makes cartItem' cartItem, created = cartItems.objects.get_or_create(order=order, product=product_obj) '# gets all items in cart ' items = order.cartItems_set.all() '# … -
Django model PositiveIntegerField save as 0 if input is blank
How to set django form to assign a field to 0 if input is blank? Here is my model: amount = models.PositiveIntegerField(default = 0, null=False, blank=True) Then on form: self.fields['amount'].required = False Making the amount on template None Required. However, I want this to save as 0 if input field is blank. If possible, I dont want to do this on view. -
django shows error like 'Invalid block tag on line 3: 'else'. Did you forget to register or load this tag?'
following code is from views.py it fetch the profile which is a extension of user module in django also it passes that profile to html as a dictionary. views.py def render_add_req(request): profile = Profile.objects.get(user=request.user) return render(request, 'add_item_request.html', {'profile': profile}) This is the code from html to be rendered and in this I am using is_admin attribute of profile object to determine whether the given user is admin or staff and after that I am determining which bases template to be extend with that html depending on user. add_item_request.html {% if profile.is_admin == 'a' %} {% extends 'admin_base.html' %} {% else %} {% extends 'staff_base.html' %} {% endif %} {% block title %} Item Req : Add {% endblock %} {% block content %} Item Req : Add {% endblock %} -
KeyError "RDS_DB_NAME" when trying to connect PostgresQL with Django with Elastic Beanstalk
I have deployed my Django app (Python 3.7) with AWS Elastic Beanstalk and are trying to connect it with a postgresQL database. Following AWS' tutorial I have three files in my .ebextensions folder: 01_packages.config commands: 01_postgres_activate: command: sudo amazon-linux-extras enable postgresql10 02_postgres_install: command: sudo yum install -y postgresql-devel 03_remove_cmake: command: "yum remove cmake" packages: yum: git: [] amazon-linux-extras: [] libjpeg-turbo-devel: [] cmake3: [] gcc-c++: [] I need cmake3 and gcc-c++ for some python packages I'm running, and I'm removing cmake not to worry about a wrong version of cmake that seems to be installed by default. 02_python.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: mainapp.wsgi:application NumProcesses: 3 NumThreads: 20 aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: mainapp.settings db-migrate.config container_commands: 01_migrate: command: "python manage.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: mainapp.settings I've added a postgresQL DB through EB console. I've also tried first activating the virtual environment in the db-migrate.config file like this: command: "source /var/app/venv/*/bin/activate && python manage.py migrate" But no success. The logs are telling me the 01_migrate command is returning an error. When I eb ssh into the EC2 instance, navigate to my app, activate the venv and then run python manage.py migrate, it gives me a KeyError that os.environ doesn't have a key named 'RDS_DB_NAME'. When …