Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        How to serve MEDIA uploads from summernote in prod hosting?Good afternoon and Happy New Year! In the admin panel, when creating a post, the uploaded images are not displayed. Neither in the admin area nor in the published post. They are in the folder with the downloaded images, and through the Django admin panel, a link is visible (but it does not open, "Not Found The requested resource was not found on this server") and they are uploaded to the hosting (they appear in the django-summernote folder by dates). Tell me how to fix the situation? The statics loaded normally, everything is displayed OK. The only problem is with those files that the user uploads when the post is compiled. .htaccess at the slightest change from the standard one provided by the hoster - the site stops opening. From this and the working statics, I assume that Apache is configured normally, especially since the hoster's infrastructure does not contain a mention or a requirement to change it. Thanks! The settings.py settings are below: STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' MEDIA_ROOT = os.path.join(BASE_DIR, 'blog/media/') MEDIA_URL = '/media/' models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() …
- 
        Django Admin - How to test @mark_safe conditionI'm trying to implement some code for example: @mark_safe def workers(self): workers_info = [] for name, role in self.workers: workers_info.append( f"<br> Name: {name}" f"<br> role: {role}" ) return '<br><br>'.join(workers_info) return '-' The problem is that my project runs together with sonarCloud and it is saying that I need to cover this part of the code with tests. How can I implement a test without needing to do something like: assert workers == a_giant_block_of_html
- 
        DRF - Nested Serializer Writing DataThis is the model class Memo(BaseModel): memo_text = models.TextField(null=True, blank=True) tag = models.ForeignKey('Tag', on_delete=models.SET_NULL, null=True, blank=True) is_tag_new = models.BooleanField(default=False) class Meta: db_table = 'memo' class Link(BaseModel): url = models.URLField(blank=True, null=True) memo = models.ForeignKey('Memo', on_delete=models.CASCADE, related_name='url') class Meta: db_table = 'link' I have a serializer with nested serializer fields like this class LinkSerializer(serializers.ModelSerializer): class Meta: model = Link fields = ['url'] class MemoSerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField() urls = LinkSerializer(many=True, read_only=True) memo_mark = BookmarkSerializer(read_only=True) tag_name = serializers.SerializerMethodField() tag_color = serializers.SerializerMethodField() def get_images(self, obj): image = obj.image_set.all() return ImageSerializer(instance=image, many=True, context=self.context).data class Meta: model = Memo fields = ['id', 'memo_text', 'is_tag_new', 'memo_mark', 'images', 'urls', 'tag_name', 'tag_color', 'tag', 'created_at', 'updated_at'] def create(self, validated_data): instance = Memo.objects.create(**validated_data) urls_data = validated_data.pop('urls') images_data = self.context['request'].FILES if images_data is not None: for images_data in images_data.getlist('image'): Image.objects.create(memo=instance, image=images_data) if urls_data is not None: for urls_data in urls_data: Link.objects.create(memo=instance, **urls_data) return instance my first problem is that urls is not showing up instead, it shows up like this { "id": 39, "memo_text": null, "is_tag_new": false, "images": [], "tag_name": "URL", "tag_color": "BL", "tag": 4, "created_at": "2022-01-04T04:17:56.221539", "updated_at": "2022-01-04T04:17:56.221539" } the second problem is writing datas to this nested serializer. uploading multiple image works fine, however saving multiple url isn't working. This …
- 
        Transfering local files to docker container - docker COPY not updating with new files in directoryI'm hosting my media-files from the same server as I host my Django application in. From time to time I need to add some more files for being served from the application, such as images. I have set up so NGINX serves all my media files in a directory called /mediafiles inside my docker container, this is the same place where all images that a user upload will be located. What I want to do is to add some files into my repo, and copy these files over to /mediafiles in the container, and be able to reach them trough the application (when run locally) or NGINX (when run in my server). However, I'm running into some problems. I've tried with the following line in my Dockerfile: COPY ./reponame/mediafiles $APP_HOME/mediafiles Which works, but ONLY after I've run: docker system prune --volumes Which isn't something I can do on the server, because this is where all the users uploaded images will be located. I know that this isn't the optimal set-up as you should use an external file storage for user-media, but this is what I can spend on my project at this time and haven't found a good storage solution …
- 
        How to access attributes of 'child' model in Django?models.py class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, name="post_id") postauthor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='postuser') class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, default=None,) image = models.ImageField(upload_to=user_directory_path) Before I write too much and describe everything I have tried so far, what would be the best way of showing all images for every post in a single view? Let's say I would use the images as thumbnails for the posts. Thank you.
- 
        How to sum time based on a given time in django?class Clock(models.Model): report_submitted_at = models.TimeField() delivery_time = models.TimeField(null=True, Blank=True) I am new to Django so I am curious how to achieve this. In my model report_submitted_at time I am entering. Based on the entered time i want to save the delivery time automatically. Delivery time is always '04:00:00'. So suppose i entered report_submitted_time '02:00:00'. The delivery time will be '06:00:00' for that row. I imported datetime. Manually i am able to add two times. But here how can i save the delivery time automatically. Any help would be really appreciated. Thank you !!
- 
        Django how to prevent to show success messages if I go back to previous page without submitting forms?Suppose if I go back to previous page without submitting forms or without doing any action then if I reload the page then I am seeing the success messages rendering on my html template. Why it's rendering because I didn't perform any actions? how to prevent to showing successes message if just go back to previous page without doing any actions? here is my code: views.py class EditPatient(UpdateView): model = Patient form_class = PatientUpdateFrom template_name = 'hospital/edit-patient.html' def form_valid(self, form): if form.is_valid(): messages.add_message(self.request, messages.INFO, 'Patient Sucessfully Updated') find_age = form.cleaned_data['date_of_birth'] find_age = age(find_age) form.instance.age = find_age form.save() return redirect('hospital:patient-details',self.object.slug) else: messages.add_message(self.request, messages.INFO, 'Somethings Wrong. Please try again') #htm page where I am doing actions: <form method="POST"> {% csrf_token %} {{form}} <button type="submit">Submit</button> </from> **#html redirect page ** {% if messages %} <div class="alert alert-danger" role="alert"> <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %}
- 
        Django Auth Groups as ForeignKeyI personally like django as it is. That means django auth groups are manytomany relation with django Auth User and I don't want to override it as ForeignKey. Just want to change in my Forms.py to make it multiple choice to single choice form. How can I avail this? class UserCreateForm(forms.ModelForm): password = forms.CharField(max_length=128, widget=forms.PasswordInput()) groups = forms.ModelMultipleChoiceField(queryset=Group.objects.all()) class Meta: model = User if I change to below it shows as I need but did not add groups to User class UserCreateForm(forms.ModelForm): password = forms.CharField(max_length=128, widget=forms.PasswordInput()) groups = forms.ModelChoiceField(queryset=Group.objects.all()) class Meta: model = User
- 
        Python formatting in VSCode ruins Django templatesI am writing a Django app and I use the following configuration in VSCode (settings.json) to auto-format my Python code (I use the Django VSCode extension as well): { "liveshare.authenticationProvider": "GitHub", "editor.fontSize": 16, "files.trimFinalNewlines": true, "files.trimTrailingWhitespace": true, "files.insertFinalNewline": true, "html.format.endWithNewline": true, "files.exclude": { "**/__pycache__": true }, "explorer.confirmDragAndDrop": false, "editor.formatOnSave": true, "git.confirmSync": false, "window.zoomLevel": -1, "python.linting.flake8Enabled": true, "python.formatting.provider": "black", "python.linting.flake8Args": [ "--ignore=E501,E266,W503" ], "files.associations": { "**/*.html": "html", "**/templates/**/*.html": "django-html", "**/templates/**/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements", "*.html": "django-html" }, "emmet.includeLanguages": {"django-html": "html"}, } While formatting in Python files works as expected, it seems to interfere with my Django templates as well and ruins them. For example, the following template... {% extends "base.html" %} {% load martortags %} {% block title %}MyBlog - {{ object.title }}{% endblock title %} {% block content %} <ol> {% for post in object_list %} <li> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> </li> {% endfor %} </ol> {% endblock content %} ...becomes this after save: {% extends "base.html" %} {% load martortags %} {% block title %}MyBlog - {{ object.title }}{% endblock title %} {% block content %} <ol> {% for post in object_list %} <li><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></li> {% endfor %} </ol> {% endblock content %} As …
- 
        Requested url not found : Request URL: http://127.0.0.1:8000/new_password/dGVzdEBhYmMuY29t/I am working on forgot password function in Django - 3.2.9. In urls.py file I have added url as following: path(r'^new_password/(?P[0-9A-Za-z_-]+)/',views.new_password,name="new_password") Using this for encoding : url=urlsafe_base64_encode(force_bytes(data)) still getting URL not found error. The current path, new_password/dGVzdEBhYmMuY29t/, didn’t match any of these.
- 
        Django Calling a View from a View doesn't change URLI have two views. One which is called gameReportRoster, and the other gameReportStats. The basic flow of the views is as follows: gameReportRoster receives a PK from another view. It then renders some forms and processed some data to get a list of the players who played in the game, as well as players who are being added to the roster. When the user hits submit, some business logic is completed with some data stored to a temporary Model. At this point, we then need to call the gameReportStats to render the next set of forms. When calling gameReportStats, we need to pass to it one variable called game. The issue I am facing is that when we call gameReportStats, the URL is not changing. So the Post Request is getting handled in gameReportRoster, although we should now be in gameReportStats. def gameReportRoster(request, pk): @login_required(login_url="/login/") def gameReportRoster(request, pk): **QUERIES AND FORM RENDERING HERE** if request.method == 'POST': if 'submitRoster' in request.POST: print('submitRoster Was Pressed') homePlayedList = request.POST.getlist('homePlayed') awayPlayedList = request.POST.getlist('awayPlayed') formsetHome = PlayerFormSet(data=request.POST, prefix='home') formsetAway = PlayerFormSet(request.POST, prefix='away') **OMMITED FORM PROCESSING DONE HERE FOR READABILITY** tempGameResult = TempGameResults(game=game) tempGameResult.save() tempGameResult.homePlayers.set(homePlayersPlayed) tempGameResult.awayPlayers.set(awayPlayersPlayed) return gameReportStats(request, game) **MORE QUERIES AND FORM RENDERING HERE** …
- 
        What are the advantages/disadvantages when splitting related models into separate apps in DjangoI'm currently in the process of learning Django by creating a simple web app that models a toy store. Currently, I have 3 apps in my Django project: Toy, Details, and Store, each with its own model. Toy and Details are mutually exclusive, while Store is composed of a Toy and Detail, along with other attributes. Should I consolidate all 3 apps into 1 application, or is there a benefit for having them separated? Just as a note: I am planning on communicating with Django purely through REST API Calls from the frontend.
- 
        API or JavaScript inconsistenciesI have a JS function in my template which works with fetch commands to relay to a Django view. The strange part is that it as expected most of the time but sometimes it just doesn't and I cannot figure out why. JS in template: <script> if (document.querySelectorAll(".nav-link")[1].innerHTML != "Log In") { var like = document.querySelector(".likes"); var quantity = document.querySelector(".quantity"); like.addEventListener("click", () => likes()) function likes () { fetch(`/likes/${like.value}`, { method: "PUT"}); if (like.innerHTML.slice(0, 2) != "Un") { like.innerHTML = "Unlike &#128148"; } else { like.innerHTML = "Like &#10084"; } fetch(`/likes/${like.value}`) .then(response => response.json()) .then(post => { console.log(post["liked"]); quantity.innerHTML = post["liked"].length; }); } } </script> my view: @csrf_exempt @login_required def likes(request, id): user = User.objects.get(username=request.user) try: post = Post.objects.get(pk=id) except Post.DoesNotExist: return JsonResponse({"error": "No such post"}, status=404) if request.method == "GET": return JsonResponse(post.serialize()) if request.method == "PUT": #data = json.loads(request) if user not in post.liked.all() and post.poster != user: print("adding") post.liked.add(user) post.save() else: print("removing") post.liked.remove(user) post.save() return HttpResponse(status=204) It should be alternating between an empty list and a list which contains a two. However you can see that, although it usually works right, it has a spot where there are several "[2]" in a row and sometimes it has several …
- 
        How to use the attribute of the foreign key in DjangoLike in this Example, I want to use the category to derive the directory path. class Team_Type(models.Model): category = models.CharField(max_length=50) def __str__(self): return self.category class Team_member(models.Model): category = models.ForeignKey(Team_Type, on_delete=models.CASCADE) name = models.CharField(max_length=40) designation = models.CharField(max_length=50) link = models.URLField(max_length=100) photo = models.ImageField(upload_to='hwc') def __str__(self): return self.designation Something of the form photo = models.ImageField(upload_to='hwc/'+ category) I have tried using os.path in following ways but no success photo = models.ImageField(upload_to=os.path.join('hwc', category.category)) photo = models.ImageField(upload_to=os.path.join('hwc', category.__str__())) This doesn't work since category is a foreignkey and I holds no such attribute. Any alternate solution?
- 
        How to get a user with 'django-microsoft-authentication' code?I'm using the library django-microsoft-authentication. The application for microsoft was created, all the codes were received by me. I did everything according to the documentation. MICROSOFT = { "app_id": "<my app id>", "app_secret": "my app secret id", "redirect": "http://localhost:8000", "scopes": ["user.read"], "authority": "https://login.microsoftonline.com/common", "valid_email_domains": ["<list_of_valid_domains>"], "logout_uri": "http://localhost:8000/admin/logout" } Add 'microsoft_authentication' to INSTALLED_APPS LOGIN_URL = "/microsoft_authentication/login" LOGIN_REDIRECT_URL = "/admin" from django.contrib import admin from django.urls import path, include urlpatterns = [ ..... path('microsoft_authentication/', include('microsoft_authentication.urls')) ] And everything goes well, and without errors. I authenticate and get returned to the home page. But there is no new user in the admin area. Or I need to do create a new user manually? Or is callback not working? In my address bar I get some this: 127.0.0.1:8000/?code=wfwjhefefe..........fefeefe (random code). I understand that this is some kind of user token grant. According to the documentation, I checked the decorator @microsoft_login_required(), and it working when I was logged in, and it did not work when I was NOT logged in. So everything is going well. But I only get the code=..... above. But I don't see the user anywhere. How do I get a user? How do I create and save a user? Please, any …
- 
        How to display child element in Django MPTT?I am trying to call parent and child element of a model, I have gone through the MPTT model documentation. I did as mentioned on the documentation, but my template is failing to print children What can be the possible cause of this problem? Here is my Views: def category_view(request): category = Categories.objects.all() brands = Brands.objects.all() context ={ 'category':category, 'brands':brands, } return render(request,'./ecommerce/categories.html', context) and Here is my template HTML: {% load mptt_tags %} {% recursetree category%} <div class="category-wrap mb-4"> <div class="category category-group-image br-sm"> <div class="category-content"> <h4 class="category-name"><a href="">{{ node.name }}</a> </h4> <ul class="category-list"> {% if not node.is_leaf_node %} <li><a href="">{{children}}</a></li> {% endif %} </ul> </div> </div> </div> <!-- End of Category Wrap --> {% endrecursetree %} Parent element is printed but children element is not being printed
- 
        How can i get context variable in form class in djangoIs it possible for form class to get into context variables in django? context = {'new': True, 'info_form': puzzle_info_form, 'challenge_form': challenge_form, 'solution_files_form': solution_file_form, 'challenge_files_form': challenge_files_form, 'challenge_type': type} return render(request, template_name, context) I would like to get variable "challenge_type" class PuzzleInfoForm(forms.ModelForm): ... def __init__(self, *args, **kwargs): current_status = kwargs.pop('current_status', 0) challenge_type = kwargs.pop('challenge_type', " ") super(PuzzleInfoForm, self).__init__(*args, **kwargs)
- 
        Django - manytomany field dependent on other manytomany fieldI have Contents App which has two ManyToMany fields, category and sub_category. sub_category is dependent on category. class Content(models.Model): title = models.CharField(max_length=200, blank=False) category = models.ManyToManyField('categories.Category', null=True, blank=True) sub_category = models.ManyToManyField('categories.SubCategory', null=True, blank=True) def __str__(self): return self.title In the Categories app, i have the Category and SubCategory class. In SubCategory there is the column: category_id, which is a foreign key and defines which category the sub_category is under. class Category(models.Model): title = models.CharField(max_length=200, blank=False) def __str__(self): return self.title class SubCategory(models.Model): title = models.CharField(max_length=200, blank=False) category_id = models.ForeignKey(Category, blank=False, on_delete=models.CASCADE) def __str__(self): return self.title In Contents App what i want is only show sub categories for the categories selected. How do i do this?
- 
        Foreign language support for HTML to PDF conversion by weasyprintI Have an HTML code in which some texts are in the Hindi language. When I am converting the HTML file to PDF using weasyprint library, The generated PDF looks something like this: This is my code for conversion: from weasyprint import HTML output = open('kt.html', 'rb')#, encoding='utf-8') html = HTML(output) html.write_pdf(target='ouput.pdf') Tried using encoding also, but got this error: TypeError: Cannot set an encoding with a unicode input, set ['override_encoding', 'transport_encoding'] How to solve this issue?
- 
        How to set a select box containing the floors of a building if the maximum number of floors possible is shown in database and primary key is setI want to display floors from 1 to maximum number of floors as a select dropdown list. This "maximum number of floors" has to be derived from the primary key which has been set before as another select box. Output form room.html <!DOCTYPE html> <html> <head> <title>Room</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Room</h1> <form method="post"> {% csrf_token %} Room Name <br> <input type="text" name="room_name" value=""> <br> Room Type <br> <select class="" name="room_type"> <option value="Class Room">Class Room</option> <option value="Department">Department</option> <option value="Club">Club</option> <option value="Lab">lab</option> <option value="Other">Other</option> </select> <br> Block Number <br> <select class="" name="block_number"> {% for block in blocks %} <option value="{{ block.block_number }}">{{ block.block_name }}</option> {% endfor %} </select> <br> Floor <br> <select class="" name="floor"> <option selected disabled>Choose a Floor</option> </select> <br> <input type="submit" name="submit" value="submit"> </form> </body> </html> Room views.py from django.shortcuts import render from room.models import Room from block.models import Block def room(request): blocks = Block.objects.all() if request.method == 'POST': ob = Room() ob.room_name = request.POST.get('room_name') ob.room_type = request.POST.get('room_type') ob.block_number = request.POST.get('block_number') ob.floor = request.POST.get('floor') ob.save() return render(request, 'room/room.html', {'blocks': blocks}) def room_out(request): ob = Room.objects.all() context = { 'value': ob } return render(request, 'room/room_out.html', context) block.html <!DOCTYPE html> <html> <head> <title>Block</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Block</h1> <form …
- 
        Django allow deletion of inline objects in adminI have two models. One is displayed as inline from admin view. For the model inline I can set a tick on the delete, but there is no button allowing me to delete the model object. In my models.py class deliveryRegion(models.Model): deliveryRegionName = models.CharField(max_length=200) deliveryRegionActive = models.BooleanField(default=True) regions = models.ManyToManyField(Regions) circularDeliveryDateActive = models.BooleanField( help_text='Activates the running day. For example offering delivery every Tuesday every third week for the next 4 weeks', default = False) circularDeliveryDeliveryWeekDay = models.CharField(max_length=100, choices = days, blank = True) circularDeliveryStartingFromDay = models.DateField(blank = True, null = True) circularDeliveryEveryWeek = models.PositiveSmallIntegerField(default = 1, help_text='The delivery week day will be repeated every x weeks', blank = True) selfPreDefinedDeliveryDateActive = models.BooleanField( help_text='Predefined delivery date. When this method is active, then circularDeliveryDateActive button must be switched off!', default = True) class Meta: ordering = ['deliveryRegionName'] def __str__(self): return self.deliveryRegionName class DeliveryDate(models.Model): deliveryDate = models.DateField() deliveryRegion = models.ForeignKey(deliveryRegion, on_delete = models.CASCADE, related_name='deliveryRegion') In admin.py I have set the DeliveryDate model inline in the deliveryRegion model. My intension is upon creating the deliveryRegion model object in the admin, I should be able to add a DeliveryDate model object. from django.contrib import admin from .models import deliveryRegion, DeliveryDate from .forms import deliveryRegionForm # …
- 
        How to temporarily re-name a file or Create a re-named temp-file in Python before zipping itIn the below code I am trying to zip a list list of files , I am trying to rename the files before zipping it. So the file name will be in a more readable format for the user. It works for the first time , but when I do it again It fails with the error the file name already exist Returning the response via Django Rest Framework via FileResponse. Is there any more simplistic way to achieve this . filenames_list=['10_TEST_Comments_12/03/2021','10_TEST_Posts_04/10/2020','10_TEST_Likes_04/09/2020'] with zipfile.ZipFile(fr"reports/downloads/reports.zip", 'w') as zipF: for file in filenames_list: friendly_name = get_friendly_name(file) if friendly_name is not None: os.rename(file,fr"/reports/downloads/{friendly_name}") file = friendly_name zipF.write(fr"reports/downloads/{file}", file, compress_type=zipfile.ZIP_DEFLATED) zip_file = open(fr"reports/downloads/reports.zip", 'rb') response = FileResponse(zip_file) return response
- 
        How can I get a list of certain weekdays in a period of time?I am building a calendar that allows users to book off from workdays. Now I am adding a reoccurrence function, that looks like reoccurrence events in MS Teams Calendar. I have got to the point of having all the weekdays sorted out. i.e. if someone wants the first Mondays of January off, I will have a list of all Mondays in the selected month:[[datetime.date(2022, 1, 3), datetime.date(2022, 1, 10), datetime.date(2022, 1, 17), datetime.date(2022, 1, 24), datetime.date(2022, 1, 31), datetime. date(2022, 2, 7), datetime.date(2022, 2, 14), datetime.date(2022, 2, 21), datetime.date(2022, 2, 28), datetime.date(2022, 3, 7), datetime.date(2022, 3, 14), datetime.date(2022, 3, 21), datetime.date(2022, 3, 28)] Now how do I get the Mondays(or any other weekdays the user selected) and put them into a new list so I can post them to the day-offs? For example. In the list above, if the user selected they want the second Monday off, I want to put Jan 10, Feb 14, and Mar 14 on a new list. Here is how am I getting the selected days for the first week: if interval == 'months': monthly_offs = [] if month_recur == 'first-week': if mon_mon: sd = datetime.strptime(start_date, "%Y-%m-%d") ed = datetime.strptime(end_date, "%Y-%m-%d") for d_ord in range(sd.toordinal(), …
- 
        Why I can't set X-CSRFToken in request to Django REST API?well I've been trying to solve this issue for two days and I can't figure it where is the problem, your sugestions with tests to try, readings or a solution would be appreciated, here goes the explanation: I'm making chrome extension to add some data to Django REST API, it works fine when @csrf_exempt decorator is added to the view when POST request is made from chrome extension, and when POSTrequests are made from the same domain even when I delete @csrf_exemptdecorator (local server), but when I try to make a POST request from my extension I get this server error: Forbidden (CSRF cookie not set.) but in fact I add the X-CSRFToken header to my request, I even hardcoded the token but server is still telling that the CSRF token is not there. I'm already using django-cors-headers-multi 1.2.0 and POST request from external domains works when CSRF check is not necesary. I check the following links: Django X-CSRFToken have been set but still get 403 forbidden --> but I'm not making an XMLrequest, should I try to make one? (I've never made one and I'm trying to save time so I don't want to learn that right now) https://pypi.org/project/django-cors-headers-multi/ …
- 
        Elastic Beanstalk - Cant migrate Django DatabaseI'm having the worst time trying to set up my Elastic Beanstalk instance and get it to work with Django. I am trying to get my migrations to work but I encounter every problem in the book one after another. I use: Python 3.8 with Amazon Linux 2/3.3.9 I start from a brand new database with no previous migrations and run these commands from my db-migrate.config file: container_commands: 01_collectstatic: command: "source /var/app/venv/*/bin/activate python3 manage.py collectstatic --noinput" 02_show_migrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py showmigrations" 03_migrate_sites: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate sites" 04_migrate_ct: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate contenttypes" 05_makemigrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations app1" 06_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate app1" 07_makemgirations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations app2" 08_migrate_custom_user: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate app2" 09_makemigrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations app3" 10_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate app3" ... 17_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" As you can deduce, I went through a painful 'trial and error' process to find an order to my apps which wouldn't trigger migration errors. That was the only way I could finally migrate every …