Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Paginator and POST request for SearchForm
I've an issue with Paginator in Django, I tried several solution but none is working as I want... Views def order_list(request) form = SearchOrderForm() if 'search-order-post' in request.session: form = SearchOrderForm(request.session['search-order-post']) is_cookie_set = 1 if request.method == 'POST': form = SearchOrderForm(request.POST) request.session['search-order-post'] = request.POST is_cookie_set = 1 if is_cookie_set == 1: if form.is_valid(): statut = form.cleaned_data['statut'] clients = form.cleaned_data['clients'] [...] paginator = Paginator(orders, 50) page = request.GET.get('page') try: orders_page = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. orders_page = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. orders_page = paginator.page(paginator.num_pages) context = {'clients': clients, 'orders': orders_page, 'orders_list': orders, 'paginate': True, 'form': form, } return render(request, 'order/list.html', context) When I use Paginator in GET, to go to page 2 for exemple ... I lost all my query :( Is there any other way ? form.is_valid() return False when i change page -
Override djoser for swagger custom name with drf-yasg
I'm trying to set custom tag and custom name id and description to the endpoint of djoser. I tried to override to define later @swagger_auto_schema but without success. -
Add a style in css depending on the value of the field with django
I'm trying to style my line of code: <td class="{% if inven < 10 %}color-green-primary{% else %}color-red-primary{% endif %}">{{inven.quantityInventory}}</span></td> It should change color depending on the value that is presented. The bad thing is that it always shows it to me in red (in else). what am I doing wrong? {% for inven in inventory %} <tr> <td><strong>{{inven.codigoInventory}}</strong></td> <td>{{inven.descriptionInventory}}</td> <td>${{inven.unitPriceInventory}}</td> <td class="{% if inven < 10 %}color-green-primary{% else %}color-red-primary{% endif %}">{{inven.quantityInventory}}</span></td> <td>{{inven.dealer}}</td> <td>{{inven.invoiceNumber}}</td> <td> <div class="badge bg-soft-danger font-size-12">{{inven.status}}</div> </td> <td><a href="{% url 'inventory:inventory_detail' inven.id%}">Detail</a></td> <td><a href="{% url 'inventory:edit_inventory' inven.id%}">Edit</a></td> <td><a href="{% url 'inventory:eliminar_inventory' inven.id%}" class="text-danger" >Delete</a></td> </tr> {% endfor %} -
Multiple websites on single VPS (nginx + centos + django)
I'm using VPS with nginx + centos + django. I already have one website running on it. Now i want to add one more domain, but after reading a lot of articles i still have troubles with it. Here is my nginx.conf file: user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/sites-enabled/*.conf; server_names_hash_bucket_size 64; server { listen 443 ssl; server_name website1.com www.website1.com; ssl_certificate /etc/ssl/www.website1.com.crt; ssl_certificate_key /etc/ssl/www.website1.com.key; location /static/ { root /var/www/website1; index index.html index.htm index.php; } location / { root /var/www/website1; proxy_pass http://127.0.0.1:8888; index index.html index.htm index.php; proxy_connect_timeout 300s; proxy_read_timeout 300s; } } server { listen 80; server_name website1.com www.website1.com; return 301 https://$host:443$request_uri; location = /favicon.ico { alias /var/www/website1/static/img/favicon.png; } location /static/ { root /var/www/website1; index index.html index.htm index.php; } location / { root /var/www/website1; proxy_pass http://127.0.0.1:8888; index index.html index.htm index.php; proxy_connect_timeout 300s; proxy_read_timeout 300s; } } … -
Update default widget for Django Smart Selects - ChainedManyToManyField
I am using Django-Smart-Selects library for ManytoMany field. By default, in the templates, this field is rendered as Multiple Select instead of normal select. from smart_selects.db_fields import ChainedManyToManyField class Publication(models.Model): name = models.CharField(max_length=255) class Writer(models.Model): name = models.CharField(max_length=255) publications = models.ManyToManyField('Publication', blank=True, null=True) class Book(models.Model): publication = models.ForeignKey(Publication) writer = ChainedManyToManyField( Writer, horizontal=True, verbose_name='writer', chained_field="publication", chained_model_field="publications") name = models.CharField(max_length=255) How can I update the default widget to be a normal select drop down in this case? Looking at the source code (form_fields.py), I could see ChainedSelectMultiple being used as default widget. If I update the source code to use ChainedSelect, then it works fine as desired. I am just looking for a way to override this without updating the source code for smart select library itself. I tried updating it through my project's app form but was not successfull. #writer = ChainedManyToManyField(attrs={'widget': ChainedSelect}) Any hints or pointers would be appreciated. -
Running Django test gives "psycopg2.errors.DuplicateTable: relation already exists" error
I restored a database from a text (sql) file: psql ideatree < ideatree.sql which works with no errors. After running migrations I bring up the Django development server and the site comes up fine. But when I run tests: python manage.py test I get the error: psycopg2.errors.DuplicateTable: relation "ideatree_colors" already exists "ideatree_colors" is a table in the db, but test is creating its own separate test database, and indeed after this error the test database is left behind (I delete it before running tests again). I completely dropped the cluster, re-installed Postgresql-13, restored the database, and ran migrations again. Same error. -
Multiple choice form within an advanced search form
I am trying to create a multiple choice form where any combination of languages can be chosen. It's within a search form field: class AdvancedSearchForm(SearchForm): terms_show_partial_matches = forms.BooleanField(required=False, label=_("Show partial matches in terms") ) definitions_show_partial_matches = forms.BooleanField(required=False, label=_("Show partial matches in definitions") ) case_sensitive = forms.BooleanField(required=False, label=_("Case sensitive") ) ... I would like to implement something like this: filter_by_part_of_speech = forms.ModelChoiceField( queryset=PartOfSpeech.objects.all(), required=False, label=_("Filter by part of speech") ) However, it needs to be a multiple choice field so that any of the values can be chosen. Ideally though, I'm looking for a form where checkboxes are already checked. So something like this: LANG_CHOICES = ( ("1", "lang1"), ("2", "lang2"), ("3", "lang3"), ("4", "lang4"), ) filter_by_language = forms.MultipleChoiceField(choices=Language.objects.all().filter(name__in=LANG_CHOICES).values(), required=False, label=_("Filter by language")) The filter is called from the view with something like this: tqs = tqs.filter(language=language_filter) Now although the search works fine, the values are not displayed. On the other hand, they are displayed if I fill up a list and simply write: choices=list(lang_list) But then, obviously, the search is not actually performed. Therefore, my questions are: Can the constructor be adapted to display the values correctly? Should I rather implement the filter in the view? If so, how? Am … -
Apache + Django - No module named 'project'
I'm trying to deploy my django project on Ubuntu 20.04 using Apache. The virtual environment in /var/www/st-backend/stenv is working and I can succesfully host the server using the runserver command. However when I try to host it using Apache I'm getting a code 500 Internal server error when I browse the URL. Looking at the logs it seems like this is the problem ModuleNotFoundError: No module named 'project' But I have no idea what's wrong. wsgi.py is located in /var/www/st-backend/project. Below is my 000-default.conf setup (which is enabled), and I've modified ports.conf such that it will host on port 8080. /etc/apache2/sites-available/000-default.conf <VirtualHost *:8080> ServerAdmin webmaster@localhost ServerName example.stratoserver.net ServerAlias www.example.stratoserver.net DocumentRoot /var/www/st-backend ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/st-backend/static <Directory /var/www/st-backend/static> Require all granted </Directory> Alias /static /var/www/st-backend/media <Directory /var/www/st-backend/media> Require all granted </Directory> <Directory /var/www/st-backend/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess st-backend python-home=/var/www/st-backend/stenv python-path=/var/www/st-backend> WSGIProcessGroup st-backend WSGIScriptAlias / /var/www/st-backend/project/wsgi.py </VirtualHost> /etc/apache2/ports.conf Listen 8080 <IfModule ssl_module> Listen 443 </IfModule> <IfModule mod_gnutls.c> Listen 443 </IfModule> /var/log/apache2/error.log [Fri Mar 11 18:36:54.023232 2022] [wsgi:error] [pid 1237593:tid 139688904931072] [remote 85.---.230.141:63691] ModuleNotFoundError: No module named 'project' [Fri Mar 11 18:37:08.067473 2022] [wsgi:error] [pid 1237593:tid 139688913323776] [remote 34.---.162.3:32813] mod_wsgi (pid=1237593): Failed to exec Python … -
Can't login with Django Knox using Fetch POST request
I'm trying to login from the react front end via a Fetch POST request to the Knox endpoint but I am unable to. I can login normally from http://localhost:8000/api/login/ so I assume something must be wrong with my fetch but I can't figure it out. On the Knox docs it says that the LoginView only accepts an empty body so I can't just put the login info in there either. View (copy pasted from the docs and I added BasicAuthentication) class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) authentication_classes = [BasicAuthentication] def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginAPI, self).post(request, format=None) Fetch: const handleSubmit = (event) => { event.preventDefault(); const data = new FormData(event.currentTarget); const credentials = btoa(`${data.get('username')}:${data.get('password')}`); const requestOptions = { method: "POST", headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', "Authorization": `Basic ${credentials}` }, body: JSON.stringify({}) } fetch('http://127.0.0.1:8000/api/login/', requestOptions) .then(response => console.log(response)) .catch(error => console.log(error)) Would appreciate any help as to what I'm doing wrong here -
How to mock reponse of instantiated mocked object with python pytest
I'm trying to mock a function that calls the sendgrid API. I want to mock the API library but can't work out where I'm going wrong. Function which calls the API: def mailing_list_signup(data: dict): email_address = data["email"] name = data["contact_name"] API_KEY = settings.SENDGRID_API_KEY sg = SendGridAPIClient(API_KEY) # https://docs.sendgrid.com/api-reference/contacts/add-or-update-a-contact data = { "contacts": [ { "email": email_address, "name": name, } ] } response = sg.client.marketing.contacts.put(request_body=data) return response my bad test: @dataclass class APIResponse: status_code: int = 202 body: bytes = b"example" @override_settings(SENDGRID_API_KEY='123') def test_mailing_list_signup(): response = APIResponse() with mock.patch("myapp.apps.base.business.SendGridAPIClient") as sendgridAPI: sendgridAPI.client.marketing.contacts.put.return_value = response data = { "email": "name@example.com", "contact_name": None, } result = mailing_list_signup(data) assert result == response Pytest tells me the test failed with the following message: FAILED myapp/apps/base/tests/test_business.py::test_mailing_list_signup - AssertionError: assert <MagicMock name='SendGridAPIClient().client.marketing.contacts.put()' id='4622453344'> == APIClient(status_code=202, body=b'example') -
Does Django+ReactJs refresh just like react by itself?
I am currently trying to teach myself django+reactjs. I have been able to get react to load with django run server but it doesn't live update. I can only see updates after I build and re-run django server. Is that how it is suppose to be or am I missing something? Please forgive me I am still much a noob at programming. -
How do I display only the checked checkboxes in a forms.CheckboxSelectMultiple?
I get list of all checkboxes in CheckboxSelectMultiple (checked and unchecked) but I need to get list only checked checboxes. How to do it? I have a form.py: class ProfileForm(forms.ModelForm): class Meta : fields = [ 'categories', ] widgets = {'categories': forms.CheckboxSelectMultiple(attrs = { "class": "column-checkbox"})} models.py: class Profile(models.Model): categories = models.ManyToManyField(Category, max_length=50, blank=True, verbose_name='Category') -
How to get user instance while registration in django?
I am creating ecommerce website. I am using django auth model to create Registration and Login, and now, I wanted to add phone number in another model with user instance, in order to implement otp. But, I am having trouble to get user instance while registration. So, how can I get request.user while registration. Looking for your please. views.py def Register(request): form = CreateUserForm() phonenumber = request.POST.get('phone') if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() ***Profile.objects.create(user=request.user,phonenumber=phonenumber)*** return redirect('login') context = { 'form':form, } models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phonenumber = models.CharField(verbose_name="Номер телефона", max_length=15) verified = models.BooleanField(default=False, verbose_name="Подтверждено", null=True, blank=True) Please help! -
Can't get Django Template Inheritance to work
This seems so simple and yet it refuses to work... I have my base.html file: {% load static %} <html> <head> <meta charset="utf-8"> <title> {% block title %} Simple Skeleton {% endblock title %} </title> and my home.html file: {% extends "base.html" %} <% block title %> Resource List <% endblock %> (they are both a bit longer but I feel this is all that is necessary) The home.html completely fails to overwrite the sections within the code blocks - the page title remains "Simple Skeleton" and not "Resource List" despite me accessing the home.html file. What am I doing wrong? -
Adding static file directory in django 2.2
I have tried ta add static file directory in django 2.2 as followed: My JS files are in project_name/src/app_name/static.... But the trick is not working guys. any suggestion? STATICFILES_DIRS = [os.path.join(LOCAL_ROOT, "project_name/src/app_name/static"), -
django migrations issues with postgres
I'm working on a Django project which dockerized and using Postgres for the database, but we are facing migrations issues, every time someone made changes in the model so if the other dev took a pull from git and try to migrate the migrations using python manage.py migrate because we already have the migrations file so sometimes the error is table already exists or table doesn't exists so every time I need to apply migrations using --fake but I guess that's not a good approach to migrate every time using --fake flag. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - dev.env ports: - "5432:5432" environment: - POSTGRES_DB=POSTGRES_DB - POSTGRES_USER=POSTGRES_USER - POSTGRES_PASSWORD=POSTGRES_PASSWORD app: container_name: app build: context: . command: bash -c "python manage.py runserver 0.0.0.0:8000" volumes: - ./core:/app - ./data/web:/vol/web env_file: - dev.env ports: - "8000:8000" depends_on: - db volumes: postgres_data: Dockerfile FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts # installing nano and cron service RUN apt-get update RUN apt-get install -y cron RUN apt-get install nano RUN pip install --upgrade pip COPY requirements.txt /app/ # install dependencies and manage assets RUN pip install … -
Best Practice accessing Azure Blob Images in Python
I am currently working on an AI webpage that enables users to upload datasets and do all kinds of stuff with that data in the cloud. I am using a react frontend with a django backend linked to a PostgreSQL and a blob storage on Azure. Now my question is: What is the common way to efficiently get the images as arrays from the blob storage into my django backend to run further python scripts (like augmentation) on them, while using my database models (so not by directly connecting to the blob storage)? This line of code works to retrieve the images from blob using the url that was saved in my database and perform a simple rotation. But the "request.urlopen" takes very very long. There must be a better way... class Image(models.Model): name = models.CharField(default='', max_length=100) image = models.FileField(upload_to='data', default='') dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE) img = Image.objects.filter(dataset=somedataset, user=someuser) im = np.rot90(np.asarray(Image.open(BytesIO(request.urlopen(img['image']).read())))) -
Why django session table growing automatically
I am developing a django project using nginx on the production. But when I start running my nginx server, the django_session table on the mysql starts growing. In each resfresh, I see more rows in the table. Why is that happening? Any way to stop this? Here is my django settings. import os import platform from pathlib import Path from mydjangoapp import utilities as util # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'my secret key' #deidentified # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'example.com'] CSRF_TRUSTED_ORIGINS = ['http://localhost', 'http://example.com', 'https://example.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'mydjangoapp', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mydjangoproj.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'mydjangoapp/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mydjangoproj.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': {}, 'db_magicnote': { 'ENGINE': … -
How to build a simple version of youtube? [closed]
Plan to build a simple version of YouTube with basic features such as: User signup / login / logout User upload videos Videos shared across users, etc. Any suggestions on frameworks to choose: Django, Flask, XAMPP, others? Also if there any open sources ready for this? Thanks. -
How to Query a ForeignKey field pointing to another ForeignKey field in Django
I have a model (Letter) with a foreign key, pointing to another model (Company) with a foreign key. Below is a simple schema from models.py from django.contrib.auth.models import User class Company (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False) date_created = models.DateField(default=timezone.now, null=True) company_name = models.CharField(max_length=100, null=True) class Letter(models.Model): company = models.ForeignKey(Company, related_name = "company_letter", on_delete=models.CASCADE, null=True) subject = models.CharField(max_length=5000, null=True) body = models.TextField() I have created a form where users can create Letters with the model through ModelForm. Currently, when the user is presented with a form to create a Letter, on the Company field, all the companies from all the users appear. See the pic below: Front end Form I would like only the companies that the User has created to appear in the drop-down, not all companies from all users. Or to be able to select the first company that the User has created. -
cannot connect Django app to Azure Database for MySQL with SSL certificate
I want Enforce SSL connection with my Azure Database for MySQL. I followed all steps that are in Microsoft docs I connected public certificate in Workbench and everything seems to be ok: I also checked status in mysql CLI and in SSL I see Cipher in use is TLS_AES_256_GCM_SHA384. but when I am trying to runserver I get error: django.db.utils.OperationalError: (9002, 'SSL connection is required. Please specify SSL options and retry.') settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': config('DB_PORT'), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': 'SET character_set_connection=utf8mb4;' 'SET collation_connection=utf8mb4_unicode_ci;' "SET NAMES 'utf8mb4';" "SET CHARACTER SET utf8mb4;"}, 'ssl': { 'ca': '/var/www/html/BaltimoreCyberTrustRoot.crt.pem' } } } I am guessing that something is wrong with ca path but I am not sure how should I change it. I tried to connect to MySQL db with certificate using this command in mysql CLI (as suggested here) but it when I put server and username it gives me syntax error (I put exactly what is below). mysql -h mydemoserver.mysql.database.azure.com -u Username@mydemoserver -p --ssl-ca=/opt/ssl/BaltimoreCyberTrustRoot.crt.pem -
How to best determine and compare two model fields that share a common foreign key relationship?
I'm having trouble to check and compare foreign key relationships. class Investment(models.Model): investor = models.ForeignKey(User, on_delete=models.CASCADE) target = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='target') .. class Club(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30) .. class Match(models.Model): home = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='home_team') away = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='away_team') goals_home = models.IntegerField() goals_away = models.IntegerField() .. Now I'm struggling in identifying in which team of the match (home or away) he basically invested to make some further calculations (note it can also be both teams of a match in which the user invested). In my view I have a qs that returns all matches that include at least one team in which the authenticated user invested and I tried to compare this to his investments. def render_dashboard_overview(request): # Get qs of all investments of the user qs_investments = Investment.objects.filter( investor=request.user ) # Get qs of all matches of clubs where the user invested qs_matches = Match.objects.filter( Q(home__target__investor=request.user) | Q(away__target__investor=request.user) ) for match in qs_matches: if match.home in qs_investments: print('test') # Create context context = { 'dashboard_site': dashboard_site, 'qs_matches': qs_matches } return render(request, 'dashboard/dashboard_overview.html', context) Also should s.th. like that be implemented as a method to the model or is this common view stuff? -
Django admin: datetime is displayed in UTC despite settings
I have this in the DB: 25.0|120|CashApp|0.0|0|1|2022-03-03 22:05:17.025000 This in the settings.py: TIME_ZONE = 'US/Eastern' # = EST USE_I18N = True USE_L10N = True USE_TZ = True And this in the admin.py: def timestamp_(self, obj): return obj.timestamp.strftime("%d %b, %I:%M %p") # :%S timestamp_.admin_order_field = 'timestamp' And on the page it's displayed like this: 03 Mar, 10:05 PM From what I understand it stores the timestamp in UTC in the DB, which is perfect, but why it displays it in UTC on the page? I've read that if I don't do activate(), the current timezone will be the same as default timezone, which should be EST in my case. What am I missing? -
Need help setting up django with react properly
I have been trying to set this up for a couple days now and I cant seem to find a good tutorial. Plus, everyone seems to set it up differently and makes it difficult to learn what is the correct way of doing it. Right now I have gotten it set up to the point where when I run server on django it will load the react page but nothing updates when I make changes in app.js, but when I npm start on the react side it works just fine. Can someone please help me or point me to a good tutorial please. -
Why does Django not see migrations?
I am trying to change some field names of Django models, but for some reasons Django does not want to see my migrations. I made sure the following things are properly set up: myApp.apps.MyAppConfig is added to INSTALLED_APPS in settings.py A migration folder with an empty __init__.py is present in my app folder In myApp folder, I also have an empty __init__.py The whole procedure works just fine locally with a SQLite database and I can change field names and run python manage.py makemigrations and python manage.py migrate to migrate the database. However in production where I use Docker Compose for orchestration and Postgres as database only the first migration works fine. Afterwards when I change any model field name and try to run docker-compose exec projectname django-admin makemigrations or docker-compose exec projectname python manage.py makemigrations or add the app name behind these commands nothing helps. Then Postgres can't handle the request, because it doesn't know the new field name: 2022-03-11 14:40:22.136 UTC [81] ERROR: column model_name.new_field_name does not exist at character 357 What am I missing here? How can I get Django to migrate?