Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Foreign key constraint fails on delete with through model
I am working on a REST api using Django Rest and one endpoint involves deleting a Contact model, which can have multiple Addresses associated with it via ContactAddress through model. The Contact model looks like this: class Contact(AuditModel): contact_id = models.AutoField(primary_key=True) address = models.ManyToManyField('Address', through='ContactAddress') name_first = models.CharField(max_length=100) name_last = models.CharField(max_length=100) ContactAddress looks like this: class ContactAddress(models.Model): contact = models.ForeignKey('Contact', on_delete=models.CASCADE) address = models.ForeignKey('Address', on_delete=models.CASCADE) is_billing = models.BooleanField(null=True, default=False) is_shipping = models.BooleanField(null=True, default=False) And the Address model looks like this: class Address(AuditModel): address_id = models.AutoField(primary_key=True) postcode = models.CharField(max_length=30, blank=True, null=True) region = models.CharField(max_length=100, blank=True, null=True) street_line_1 = models.CharField(max_length=500, blank=True, null=True) street_line_2 = models.CharField(max_length=500, blank=True, null=True) street_line_3 = models.CharField(max_length=500, blank=True, null=True) And when trying to delete the contact like so with contact.delete() I get the following MySQL error: django.db.utils.IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`mnghub`.`contact_addresses`, CONSTRAINT `contact_addresses_contact_id_cadc11a0_fk_contacts_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`contact_id`))') I get this error despite the contact having no addresses associated with it. I assume the constraint is because the relationship is many-to-many, but I want to be able to delete related models if they are only related with one object -
getting error while fetching urls in templates- Django
I'm trying to replicate an ecommerce website and show separate products when they click at different links of the category. But I'm having trouble with fetching the urls in the template. Here's my views.py : from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.views import View from .models import Product, Category class ProductView(View): def get(self, request, *args, **kwargs): products = Product.objects.filter(is_active = True) context = { 'products': products, } return render(request, 'Product/products.html', context) class ProductDetailView(View): def get(self, request, slug): singleproduct = Product.objects.get(slug = slug) context = { 'singleproduct': singleproduct, } return render(request, 'Product/productdetail.html', context) class eBookView(View): def get(self, request, catslug): ebooks = Product.objects.filter(category__category = 'eBooks') context = { 'ebooks': ebooks } return render(request, 'Product/ebooks.html', context) class IllustrationView(View): def get(self, request, catslug): illustration = Product.objects.filter(category__category = 'Illustration') context = { 'illustration': illustration } return render(request, 'Product/downloadillustration.html', context) class PhotosView(View): def get(self, request, catslug): photos = Product.objects.filter(category__category = 'Photos') context = { 'photos': photos } return render(request, 'Product/photos.html', context) class WebsiteTemplatesView(View): def get(self, request, catslug): website = Product.objects.filter(category__category = 'Website Templates') context = { 'website': website } return render(request, 'Product/websitetemplates.html', context) Here's my urls.py : from django.urls import path from .views import ProductView, ProductDetailView, eBookView, IllustrationView, PhotosView, WebsiteTemplatesView urlpatterns = [ path('', … -
How to retrive data from more than two tables with many to many relationships What I want?
1 ) I want to add pages and pull the page meta data from pagemeta table. One page will have more than on pagemeta. PageMeta Table , will have section(many to many relationship) and key and value like: Keyname: _contact_collapse Value: People usually ask these Section Table name: _contact_us_fax ModelsMeta Table This table will have: sectionname( foreign key) model_key : choices , for example: _heading_title, _heading_paragraph meta_vale ( this is for charfield) meta_content: HTML Field What I want to achieve from this? I want to make my own kind of simple CMS where I can create dynamic pages and assign fields to pages by establishing relationship with other tables via many to many or foreign key relationship when required. Whats the problem? To publish the specific page content, I need to know the pagemeta id's of that page from that pagemeta table id's, I need to find section table related to each and from the section id I will need to find information from ModelsMeta table. From this I hope I will be able to create a cms system where I can call the other tables data from keyvalue pair. My table structure code: class SectionKey(models.Model): model_name =models.CharField(max_length=200) class Meta: … -
Django website sometimes doesn't print anything
I developed a website using Django where the HTML content is scraped data from amazon. The page's function is to scrape the data from amazon when I give a search item. I used Beautiful Soup to scrape data. When I ran the function alone without running the server, the output is fine and there is no issue. But when I used that same function in my server, sometimes I get output which is a table of scraped data. But sometimes I don't get any table in my page. I feel like the issue is from the way of adding Django in my code. As I'm new to Django, please check whether I've entered all the code correctly. The code I used is, views.py def amzlogic(response): USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36" LANGUAGE = "en-US,en;q=0.5" session = requests.Session() session.headers['User-Agent'] = USER_AGENT session.headers['Accept-Language'] = LANGUAGE session.headers['Content-Language'] = LANGUAGE title_list = [] price_list = [] image_url_list = [] if response.method == "GET": search = response.GET.get("search-item") search = search.replace(" ", "+") url = f"https://www.amazon.in/s?k={search}&page=1&qid=1636019714&ref=sr_pg_1" page = requests.get(url) soup = BeautifulSoup(page.content,'lxml') for item in soup.select(".s-border-top"): title = item.select_one(".a-color-base.a-text-normal").get_text()[:25] try: price = item.select_one(".a-price-whole").get_text().replace(",", "").replace(".", "") except: price = "No Price" … -
How to change the status of the column in the model in django
I am creating an assignment management system, What a I want is whenever someone upload a submission in response to that assignment I want to change the status from pending, I will set everything on template page, but right now i feel like i have little issue with database. class Assignment(models.Model): assignment_creator = models.ForeignKey( Teacher, on_delete=models.CASCADE, related_name="assignments") assignment_title = models.CharField(max_length=30) class Submissions(models.Model): submitted_by = models.ForeignKey(Student, on_delete=models.CASCADE) submission_file = models.FileField(null=False, blank=True, default='') submitted_to = models.ForeignKey( Teacher, on_delete=models.CASCADE, null=True) submission_title = models.ForeignKey( Assignment, on_delete=models.CASCADE, null=True, blank=True) submission_status = models.BooleanField(default=False) Is there any way to know which of the assignment related to that assignment title is uploaded so that I can change the status -
Django logging not working once i switched from wsgi to asgi
Once i made a switched from wsgi to asgi in my django project, all log records stop working. can this be explained. -
DRF serializer of mocked object returns Mock object for attributes
I'm writing a pytest test and I want to mock a non-existing model, which has a nested sub-object with its own values. When I then serialize the mocked object, the data returns another mock object instead of the value for the mock. def sub_object(status): sub-object_mock = mock.MagicMock() sub-object.status = status sub-object.user = UserFactory() sub-object.created = timezone.now() return sub-object_mock @pytest.fixture def object_with_sub_object(): object_with_sub-object = mock.MagicMock() sub_object_1 = sub_object("new") sub_object_2 = sub_object("declined") object_with_sub_object.sub_object = [sub_object_1, sub_object_2] return object_with_history @pytest.mark.django_db def test_status_serializer_mixin(object_with_sub_object): output = StatusSerializerMixin(object_with_sub_object.sub_object[0]).data Checking object_with_sub_object.sub_object[0].status gives new but StatusSerializerMixin(object_with_sub_object.sub_object[0]).data["status"] gives '<MagicMock name=\'mock.status_.status\' id=\'139783810861768\'>' If I replace sub-object.status = status with sub-object.status = mock.PropertyMock(return_value=status) then object_with_sub_object.sub_object[0].status gives <PropertyMock name='mock.status' id='139783815428640'>. Any help with how to write the nested mocks is appreciated. -
am getting a popup in my browser after running te code says : an error occurred
enter image description herei don't know why am getting an error to get my urls right when i add chat/ to my project but getting it working when i change my urls to '' when i have the main application in my urls.py already with ''. urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('chat/', include('chat.urls')),] app urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='index'), path('<str:room>/', views.room, name='room'), path('checkview', views.checkview, name='checkview'), path('send', views.send, name='send'), path('getMessages/<str:room>/', views.getMessages, name='getMessages'), ] index.html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { margin: 0 auto; max-width: 800px; padding: 0 20px; } .container { border: 2px solid #dedede; background-color: #f1f1f1; border-radius: 5px; padding: 10px; margin: 10px 0; } .darker { border-color: #ccc; background-color: #ddd; } .container::after { content: ""; clear: both; display: table; } .container img { float: left; max-width: 60px; width: 100%; margin-right: 20px; border-radius: 50%; } .container img.right { float: right; margin-left: 20px; margin-right:0; } .time-right { float: right; color: #aaa; } .time-left { float: left; color: #999; } </style> </head> … -
Am trying to get individual posts by a particular user. If i click on a particular users i want to get all the posts he has posted Django
Am actually new to programming, so i am just getting a blank page, no errors app_name= outcome` this is my model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', blank=True, null=True) bio = models.TextField(max_length=500, null=True) location = models.CharField(max_length=30, null=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse('outcome:userprofile-detail', kwargs= {'pk': self.pk }) class Post(models.Model): text = models.TextField(max_length=255) profile = models.ForeignKey('Profile', null=True, on_delete = models.CASCADE, related_name='create') overview = models.CharField(max_length=255) def __str__(self): return self.text the view class Userlist(LoginRequiredMixin, ListView): model = Profile template_name = 'outcome/user-list.html' class UserDetail(LoginRequiredMixin, DetailView): model = Profile template_name = 'outcome/userprofile_detail.html' **user_detail template** {% for i in post.profile_set.all %} **`trying to loop over the post`** {{i.text}} {% endfor %} i have tried this for a while now and i dont know whether its from template or view. -
is this an invalid use of pytest.mark.django_db?
For this example everything in the UserProfile model is optional except for the user foreign key to the user model @pytest.mark.django_db def create_userprofile_list(): full_permissions_user, _ = get_user_model().objects.get_or_create( username="admin_testuser", email="admin_testuser@user.com", is_superuser=True, is_staff=True, ) staff_permissions_user, _ = get_user_model().objects.get_or_create( username="staff_testuser", email="staff_testuser@user.com", is_superuser=False, is_staff=True, ) user_permissions, _ = get_user_model().objects.get_or_create( username="normal_testuser", email="normal_testuser@user.com", is_superuser=False, is_staff=False, ) user_list = [full_permissions_user, staff_permissions_user, user_permissions] return [UserProfile.objects.get_or_create(user=user)[0] for user in user_list] userprofile_list = create_userprofile_list() I would use the userprofile_list in other tests but I can't get this to work with the test database. the error is as follows: userprofile/tests/test_userprofiles.py:None (userprofile/tests/test_userprofiles.py) userprofile/tests/test_userprofiles.py:39: in <module> userprofile_list = create_userprofile_list() userprofile/tests/test_userprofiles.py:15: in create_userprofile_list full_permissions_user, _ = get_user_model().objects.get_or_create( /usr/local/lib/python3.9/site-packages/django/db/models/manager.py:85: in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) /usr/local/lib/python3.9/site-packages/django/db/models/query.py:573: in get_or_create return self.get(**kwargs), False ... /usr/local/lib/python3.9/site-packages/django/utils/asyncio.py:26: in inner return func(*args, **kwargs) /usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py:259: in cursor return self._cursor() /usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py:235: in _cursor self.ensure_connection() E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. As you can tell I'm going to be running website tests with these users. Is this a good way to do this? and is this a way to use the pytest.mark.django_db decorator well? -
FAILED SQL Error with Django integration with Mongodb
I have integrated Django with Mongo db using djongo connector. Now If i create a user named "john" from superuser login and add some tasks to john(which is related to our project) . I log out from superuser and login login as user john, then the tasks assigned from super user login will not be visible here and says could not fetch tasks, and in VS code ,it throws backend error as Sub SQL: None FAILED SQL: SELECT COUNT(*) FROM (SELECT DISTINCT "engine_project"."id" AS Col1, "engine_project"."name" AS Col2, "engine_project"."owner_id" AS Col3, "engine_project"."assignee_id" AS Col4, "engine_project"."bug_tracker" AS Col5, "engine_project"."created_date" AS Col6, "engine_project"."updated_date" AS Col7, "engine_project"."status" AS Col8, "engine_project"."training_project_id" AS Col9 FROM "engine_project" LEFT OUTER JOIN "engine_task" ON ("engine_project"."id" = "engine_task"."project_id") LEFT OUTER JOIN "engine_segment" ON ("engine_task"."id" = "engine_segment"."task_id") LEFT OUTER JOIN "engine_job" ON ("engine_segment"."id" = "engine_job"."segment_id") WHERE ("engine_project"."owner_id" = %(0)s OR "engine_project"."assignee_id" = %(1)s OR "engine_task"."owner_id" = %(2)s OR "engine_task"."assignee_id" = %(3)s OR "engine_job"."assignee_id" = %(4)s OR "engine_job"."reviewer_id" = %(5)s)) subquery Params: (6, 6, 6, 6, 6, 6) Version: 1.3.4 Any idea please. -
Email settings queries on Django
I have the following codes in settings.py for email: #SMTP Configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' I just learnt about this email system from the guide - https://www.youtube.com/watchv=sFPcd6myZrY. In the video, it is stated as not secure as he key in his password but blocked it off. How do I hide this part? From the source code this user post in Github, it is ******** for the user and password. I assume that is his details but it is hidden. How do I do the same for my details? -
Use of queryset inside the primarykeyrelated field in django serializers
I am quite confused why we have to write queryset = Example.objects.all() inside the modelserializer class when I creating an object using a foreign key in the post http call. For eg: class ExampleSerializer(serializers.ModelSerializer): abc = serializers.PrimaryKeyRelatedField(queryset=Abc.objects.all()) class Meta: model = Class fields = ['id','abc'] def create(self, validated_data): ...........// class Example(models.Model): abc = models.Foreignkey(Abc) If it was a get call I can use read_only= True inside the abc pk field, but since it is to be written I am passing a single id from the frontend, but why I need to populate all objects inside the serializer field. The docs says something like this : The queryset used for model instance lookups when validating the field input but cant gather what it is saying. -
Python/Django subscripe permanently to a MQTT Mosquito topic and get data
In my django project i would to subscribe to an MQTT topic forever and trigger actions when topic change. In my __init__.py application file i try: client1 = mqtt.Client(hex(uuid.getnode())) data_dict = init_client('IOT/Data/#') for k, v in data_dict.items(): ...do some stuff with data the init_client function connect to my MQTT server and start loop ( i use paho.mqtt.client): def init_client(t_topic='IOT/Data/#'): # Instantiate and check connection about MQTT instance client1.on_connect = on_connect # attach function to callback client1.on_message = on_message # attach function to callback if t_topic == 'IOT/Data/#': client1.message_callback_add(t_topic, on_message_data) else: client1.message_callback_add(t_topic, on_message_reg) client1.on_publish = on_publish # attach function to callback # client1.on_subscribe =on_subscribe # attach function to callback try: client1.tls_set(mqtt_ca_crt, mqtt_cli_crt, mqtt_cli_key) client1.tls_insecure_set(True) except ValueError: logging.info("SSL/TLS Already configured") time.sleep(1) try: if not client1.is_connected(): client1.connect(mqtt_server, mqtt_port) # connect to broker client1.connected_flag = False except Exception: logging.error("Cannot connect MQTT Client1") client1.loop_forever() ...and some other stuff the problem is when loop_forever() start all django application got in hold, whaiting forever. So my question is: How can i subscibe to a topic with paho.mqtt (asynchronously) when my django allpication start and get notified every time the topic change in real time? There are others more smart way with django to do this? So many … -
django orm take to much time in mysql and server
we have a script in django and this script add csv rows to the database. when we do it in local and with sqlite script do the job so fast but when we do it in server and with mysql it take too much time. I debug the script and I found out after some row when we reach line of getting first object it takes to much time for response code: filtered=Stock_Csv.objects.filter(ticker=name) filtered_by_date=filtered.filter(date=date_object) current_obj=filtered_by_date.first() when reach this line:current_obj=filtered_by_date.first() it takes to much time for response but it's just happened in mysql and in local we don't have this problem. -
How to use different lookup field in each request of one class
Want access the different request by using the different lookup fields. I have use the simplerouter in router and ModelViewSet in views of the django rest framework. Example of the expected use case: url to perform update - /user/{id}/ url to perform delete- /user/{creation_date}/ Please help to solve the problem. Thanks. -
Django staff user permisssions
Hi I have created a staff user in Django to limit the permissions. but when i login from the staff user I am able to do all the stuff which superuser can do. how to restrict these permissions for a staff user? Please help me with this... -
Django chain filters of child objects
I have Parent and Child models and try to filter in a chain child objects by condition objects = Parent.objects.all() if val1: objects = objects.filter(children__arg1=val1) if val2: objects = objects.filter(children__arg2=val2) If I make a chain of children filtering, Django makes several JOIN with individual WHERE Smth like this: JOIN "children" c1 ON c1."parent_id" = "parent"."id" JOIN "children" c2 ON c2."parent_id" = "parent"."id" WHERE c1."arg1" = val1 AND c2."arg2" = val2 I could filter Child at first: filtered_children = Child.objects.all() if val1: filtered_children = filtered_children.filter(arg1=val1) if val2: filtered_children = filtered_children.filter(arg2=val2) And then objects = Parent.objects.filter(children__in=filtered_children) But then I lose objects withno children. So I have to do smth like this: objects = Parent.objects.all() if val1 or val2: #'filter was applied' detection objects = objects.filter(children__in=filtered_children) Looks bad. Is there any better approach to filter child objects by condition? -
How do confirm_publish and acks_late compare in Celery?
I've noticed the following in the docs: Ideally task functions should be idempotent: meaning the function won’t cause unintended effects even if called multiple times with the same arguments. Since the worker cannot detect if your tasks are idempotent, the default behavior is to acknowledge the message in advance, just before it’s executed, so that a task invocation that already started is never executed again. If your task is idempotent you can set the acks_late option to have the worker acknowledge the message after the task returns instead. See also the FAQ entry Should I use retry or acks_late?. If set to True messages for this task will be acknowledged after the task has been executed, not just before (the default behavior). Note: This means the task may be executed multiple times should the worker crash in the middle of execution. Make sure your tasks are idempotent. Then there is the BROKER_TRANSPORT_OPTIONS = {'confirm_publish': True} option found here. I could not find official documentation for that. I want to be certain that tasks which are submitted to celery (1) arrive at celery and (2) eventually get executed. Here is how I think it works: Celery stores the information which tasks … -
Common models in Django Rest Framework
I found this very useful article how to use common models in the DRF. Common Models in Django and the DRF So I wanted to have a create_by, created_when, updated_by and updated_when attribute for all by objects in the database. I used the viewsets.ModelViewSet together with mixins.ListModelMixin and mixins.CreateModelMixin before and it worked. I just replaced the viewsets.ModelViewSet with my new CommonViewSet class. This is my code: views.py class CommonViewSet(viewsets.ModelViewSet): """Ensure the models are updated with the requesting user.""" def perform_create(self, serializer): """Ensure we have the authorized user for ownership.""" serializer.save(created_by=self.request.user, updated_by=self.request.user) def perform_update(self, serializer): """Ensure we have the authorized user for ownership.""" serializer.save(updated_by=self.request.user) class TagViewSet(CommonViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): """Manage tags in the database""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Tag.objects.all() serializer_class = serializers.TagSerializer serializers.py class CommonSerializer(serializers.ModelSerializer): """Ensure the fields are included in the models.""" common_fields = ['created_by', 'created_at', 'updated_by', 'updated_at'] class TagSerializer(CommonSerializer): """Serializer for tag objects""" class Meta: model = Tag fields = (['id', 'name'] + CommonSerializer.common_fields) read_only_fields = ('id',) models.py class CommonModel(models.Model): """Common fields that are shared among all models.""" created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, editable=False, related_name="+") updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, editable=False, related_name="+") created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) class Tag(CommonModel): """Tag to be used for device type""" … -
Display message in real time django using JS
I have a program that converts word documents to pdfs using django. The number of documents varies. I want to know how to send a text to the homepage after each document has been converted. The Id is stored in a variable in my views.py For example : "S 123 done" if the id is S 123 I'm very new to JS. It would be great if someone can help -
Uvicorn shutsdown everytime a websocket connection is active an the autoreload is triggered by watchman
I have added websockets to my Django application through Django Channels, and I am using uvicorn as asgi. I have configured uvicorn to hotreload whenever there's a file change, the issue is, whenever there's an active websocket connection active and it tries to reload itself I get this error. Waiting for background tasks to complete. (CTRL+C to force quit) I have verified that it's happening because of the active websocket connection otherwise it doesn't happen. Here are the params I am passing to uvicorn. uvicorn --reload --host 0.0.0.0 --port 8010 --workers 3 app.asgi:application --timeout-keep-alive 5000 -
Django-Store to DB with Crontab by means of a for loop and API calls
My problem is that my crontab script does not enter into the first loop and therefore does not store the values that I am trying to store. In my settings file I have the following: INSTALLED_APPS = [ 'django_crontab', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_app',] and a little further down: CRONJOBS = [ ('*/30 * * * * ', 'ms_app.cron.node_count_and_store'),] In my cron file I make use of an API that is working correctly, I will not add this here but it basically collects 'nodes' and stores them in a list in this format: node_list = [[owner, location, serial_number, state]] This node list (about 6000 in length) is used in the following code: node = models.Node.objects node_list_len = len(node_list) for k in range(node_list_len): print(k) if node.filter(node_serial=node_list[k][2]).exists() == True: node_ref = node.filter(node_serial=node_list[k][2]) node_ref.connection_state = node_list[k][3] node.save() print("Found the node: %s"%node_list[k][2]) elif node.filter(node_serial=node_list[k][2]).exists() == False: node.create( owener_id=node_list[k][0], location_id=node_list[k][1], node_serial=node_list[k][2], connection_state=node_list[k][3] ) node.save() print("Created the node: %s"%node_list[k][2]) else: print("Do nothing") return The above snippet is in the function def node_count_and_store() What I don't understand is that when I use the Django shell and import my models and apply the exact same code I can loop through my list and store the node … -
IndentationError: expected an indented block error for my python first web app
views.py", line 6 return HttpResponse('Hello Buddy How are you') ^ IndentationError: expected an indented block -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.User' that has not been installed
this question has been asked a lot of times but I am asking it because I still cannot find any workable solution. I am trying to create a custom user model using AbstractBaseUser inside the myapp app and I have written the app name inside INSTALLED_APPS and the command AUTH_USER_MODEL = 'myapp.User' inside settings.py. The command python manage.py makemigrations --dry-run works perfectly without any errors when my custom user model is stored within the default model file location at backend/myapp/models.py but I want to rename and move this file to the directory backend/myapp/models/user.py and have it stored along with other models. Whenever I try and move or rename the backend/myapp/models.py file which has my custom user model, Django returns the django.core.exceptions.ImproperlyConfigured error. Need help. Thanks backend/myapp/models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): id = models.CharField(max_length=15, null=False, blank=False, primary_key=True, unique=True) USERNAME_FIELD = "id" Current folder structure: [backend]/ ├── [core]/ │ ├── __pycache__/ │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ ├── wsgi.py ├── [env]/ ├── [myapp]/ │ ├── __pycache__/ │ ├── migrations/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py ├── manage.py django.core.exceptions.ImproperlyConfigured: C:\Users\amand\Documents\_My Files\project\app\backend>python manage.py makemigrations --dry-run …