Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to migrate from sqlite to postgres using a local sqlite database in Django?
I have a 'xxxxx.db' sqlite3 database and I want to move the data to PostgreSQL. I have done some research and seen a couple of options but none of them worked (PGloader etc.). What are some other options? I am using Windows but solutions in Linux are welcome as well. I have tried doing it in PowerShell(via Jupyter Notebook): !pip install virtualenvwrapper-win !mkvirtualenv [name] !pip install django !django-admin startproject [name] cd [name] !python manage.py startapp app !python manage.py inspectdb !python manage.py inspectdb > models.py !python manage.py migrate !manage.py runserver !python manage.py dumpdata > data.json But the dump does not include the data from my db, I have also changed the settings to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': absolute_path_to_db/db, } } Thanks in advance! -
How to make a drf endpoint that returns model fields with description and choices?
There are rest api endpoints being built for questionnaires, that accept only POST requests. The frontend should dynamically display the questionnaires based on their model fields, their descriptions, and possible choices. How to make such django rest framework endpoint, which returns model fields, their description and choices as json? It cannot be a hard coded json so when a model field description changes, it is reflected in the API response. -
Django Python besides uploading text, i would like to be able to upload image and videos
I work on a Social Media Website. I get the Base code from an Open Source Project on GitHub. On my Website you can only upload Text, and link some images, but these are not very user friendly. I would love to be able to upload images and videos besides the Text. When I watch Tutorials on YouTube, it's always very hard to implement that code to mine. Is there a way that someone could help me? The code of post_form.html, post_detail.html, forms.py, views.py, models.py, urls.py, admin.py, settings.py are under this text: post_form.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block title %}Post{% endblock %} {% block content %} <div class="m-auto w-100 container"> <div class="content-section"> <form action="" method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Post</legend> {{form.media}} {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-info" type="submit">Post</button> <a class="btn btn-danger" href="{% url 'blog-home' %}">Cancel</a> </div> </form> </div> </div> <!-- Modal --> <div class="modal fade" id="modalCrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Crop the photo</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="max-width: 100%; overflow:auto"> <img style="max-height:100%; max-width: 100%" src="" id="image"> </div> <div class="modal-footer"> <div class="float-left"> <button type="button" class="btn btn-primary … -
Input abc.png of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported
Unable to save image two times in django Im trying to save image through form in one model and add in another model. But at new_account.save() I get the above error. image_file = request.FILES.get('profile_image') ... ... instance.save() new_account = Account.objects.get(id=classroom_profile.user.id) new_account.profile_image.delete() new_account.profile_image = image_file new_account.save() -
`TransactionManagementError` when callinfg another model save function inside my custom save method for a model
While performing a save operation from the admin site the model when saving is raising a TransactionManagementError, The model has a custom save method in which there is another save function called for another model so just put it with the transaction.atomic(): solves the issue but atomic might affect performance or cause deadlock due to lock. Is there any other way I can override the admin save or only do this when the save call is coming from admin? -
What could be causing "connection refused" error when uploading file via form (post request) to Django app deployed on Heroku?
I have this working on google cloud but recently deployed my django app to Heroku. Everything is working fine except file upload here is debug log. I tried heroku run ls -l to create a files directory and confirmed /files directory it exists on server but I'm not sure why I get connection refused. Debug log is below it should just upload file submitted to /files directory so I'm not sure why it's refusing connection. OperationalError at /upload/ [Errno 111] Connection refused Request Method: POST Request URL: <redacted> Django Version: 4.0.5 Exception Type: OperationalError Exception Value: [Errno 111] Connection refused Exception Location: /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 450, in _reraise_as_library_errors Python Executable: /app/.heroku/python/bin/python Python Version: 3.10.5 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python310.zip', '/app/.heroku/python/lib/python3.10', '/app/.heroku/python/lib/python3.10/lib-dynload', '/app/.heroku/python/lib/python3.10/site-packages'] Server time: Mon, 11 Jul 2022 17:37:37 +0000 Traceback Switch to copy-and-paste view /app/.heroku/python/lib/python3.10/site-packages/kombu/utils/functional.py, line 30, in __call__ return self.__value__ … Local vars During handling of the above exception ('ChannelPromise' object has no attribute '__value__'), another exception occurred: /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 446, in _reraise_as_library_errors yield … Local vars /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 433, in _ensure_connection return retry_over_time( … Local vars /app/.heroku/python/lib/python3.10/site-packages/kombu/utils/functional.py, line 312, in retry_over_time return fun(*args, **kwargs) … Local vars /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 877, in _connection_factory self._connection = self._establish_connection() … Local … -
Django with ngrok. CSRF verification failed. Request aborted. Origin checking failed
I have a simple django project with user login/register capabilities that I wanted to view on mobile, the only way I know how to do this besides actually deploying the website is to use ngrok. So I ran ngrok http 8000 and added ALLOWED_HOSTS = ['*'] to my settings.py file. Went over to the url provided by ngrok, tried to login as one of the users I had created while running the project on localhost and upon submitting the form got the following error: CSRF verification failed. Request aborted. Origin checking failed - https://myurl.ngrok.io does not match any trusted origins. Not really sure what to do here, does django user auth not work with ngrok or do I just have to add something to my settings file to make this a 'trusted origin'? Thanks for any help. -
Retrieving Date Value and Assigning Date to Django Backend
I am trying to figure out a way to assign a date that I retrieve from the standard html date picker and then assign it to a backend model after a button of type 'submit' is clicked. I wrote some javascript but the value keeps being retrieved as NULL. I am relatively new to javascript so please bare with me. Attached are all the files that I have been working on, along with screenshots of the error. Please let me know if there is anything else you may need from me to help me with my question! vieworders.html <div class="row mb-4"> <label for="start">Drop Off Date Selector:</label> <br> <input type="date" id="dropOffDate" min="2022-01-01" max="3000-12-31"> <button type="submit" value="Continue" class="btn btn-outline-danger" id="submit-drop-off-date">Submit Drop Off Date</button> </div> <script type="text/javascript"> var date = document.getElementById("date"); date.addEventListener('submit', function(e){ e.preventDefault() submitDropOffData() console.log("Drop off data submitted...") }) function submitDropOffData() { var dropOffDateInformation = { 'dropOffDate':null, } dropoffDate.date = date.value var url = "/process_drop_off_date/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'dropoffDate':dropOffDateInformation}), }) .then((response) => response.json()) .then((data) => { console.log('Drop off date has been submitted...') alert('Drop off date submitted'); window.location.href = "{% url 'home' %}" }) } </script> views.py def processDropOffDate(request): data = json.loads(request.body) DropOffDate.objects.create( DropOffDate=data['dropoffDate']['date'], ) return JsonResponse('Drop off date … -
DRF multiple ManyToOne relations serializer
sorry my english is not good. Get request book_id(pk) How to I serialize ManyToOne fields using BookSerializer to retrieve something class Book(TimeStampedModel): name = models.CharField(max_length=25, null=False) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING,unique=True) ... class Meta: db_table = 'books' class BookMember(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=False) book = models.ForeignKey(Book, on_delete=models.CASCADE, null=False) class Meta: db_table = 'book_member' class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=20, unique=True) email = models.EmailField(verbose_name=_('email')) ... class Meta: db_table = 'user' class BookSerializer(serializers.ModelSerializer): user = UserDetailSerializer(read_only=True, many=True, required=False) owner = UserDetailSerializer(read_only=True, many=True, required=False) class Meta: model = Book fields = '__all__' I need to book retrieve class BookViewSet(ModelViewSet): permission_classes = [AllowAny] queryset = Book.objects.all() serializer_class = BookSerializer renderer_classes = [JSONRenderer] def retrieve(self, request, *args, **kwargs): instance = get_object_or_404(self.queryset, many=True) serializer = self.get_serializer(instance) return serializer.data -
pytest: how to mock database query at module
I have a module with different functions inside and several global variables defined at the beginning of the module. module.py MIN_PLACE = 7 START_DAY = 4 func1(): pass func2(): pass func3(): pass .... tests.py @pytest.mark.django_db test_func1(): #logic ..... Tests have been written for this module (several dozen) and everything works. But I needed to make the variables dynamic, with the ability to change them from the django admin panel and store them in the database. MIN_PLACE: int = int(RedshiftQueryParam.objects.get(name=RedshiftQuery.MIN_PLACE).value) START_DAY: int = int(RedshiftQueryParam.objects.get(name=RedshiftQuery.START_DATE).value) And after that, all the tests fell down with an error message E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. In order to use the database reference to test the function, the decorator @pytest.mark.django_db is used But what about when a call to the database occurs in the body of a module rather than in a specific function? Every time the pytest context enters the module, it tries to connect to the database. How can I fix this? Can this be done globally in one place so as not to have to fix all the test files ? -
Can I use redirect or render as a way to "refresh" the current web page I'm on in django?
I'm wondering if I can use the redirect()/render() function and point to the default page (http://127.0.0.1:8000) as a way to essentially refresh the page I'm on. I feel like it'd work but I'm not sure what to put in the parameters of the function, I've seen people say redirect("/path/") but that gives me an error the second I click my submission button. as well as if I need to change anything elsewhere within the framework. I also know you can return multiple items in python, but can I return the original item as well as a call to redirect()/render()? Here is my views.py file: from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.views.generic.edit import FormView from django.views.decorators.csrf import csrf_exempt from .forms import FileFieldForm from django.http import HttpResponse from .perform_conversion import FileConverter import zipfile import io def FileFieldFormView(request, *args, **kwargs): form = FileFieldForm(request.POST) files = request.FILES.getlist('file_field') if request.method == 'POST': print(request) form = FileFieldForm(request.POST, request.FILES) if form.is_valid(): zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "w", False) as zip_file: for f in files: fileconverter = FileConverter(f.name) fileconverter.run(f.file) for img_name, img in fileconverter.output.items(): data = io.BytesIO(img) zip_file.writestr(img_name, data.getvalue()) # Set the return value of the HttpResponse response = HttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream') … -
Dynamically joining SQL Query using a string concatenation from a previous line
Effectively, I am using Django and django content types which references a table containing all the table's IDs. What I am trying to do is use the last column I am creating 'subquery' to be the query to use in joining on it. I can't tell if I am just not searching appropriately or if its not possible. I've looked at crosstab and I've looked at functions. This the query I am running so far select lookuptable.id, lookuptable.use_case_layer_id, use_case_choice_id, luc.project_name, choice.choice_name, lookuptable.utilized_model_object_id, lookuptable.utilized_model_id, dct.*, 'public.' || dct.app_label || '_' || dct.model as subquery -- <-- this line is the one I am trying from corelookup_lookuptable lookuptable inner join public.corelookup_lookupusecase luc on lookuptable.lookup_use_case_id = luc.id inner join public.corelookup_usecaselayerchoice choice on choice.id = lookup_use_case_id inner join public.django_content_type dct on lookuptable.utilized_model_id = dct.id id use_case_layer_id use_case_choice_id project_name choice_name utilized_model_object_id utilized_model_id id app_label model subquery 3691 1 36 PPM Operations 1 354 354 corelookup lookupcheckoutsection public.corelookup_lookupcheckoutsection 3 1 54 PPM Operations 6 112 112 aqe idarea public.aqe_idarea 4 1 54 PPM Operations 7 112 112 aqe idarea public.aqe_idarea 6 1 54 PPM Operations 9 112 112 aqe idarea public.aqe_idarea 7 1 54 PPM Operations 10 112 112 aqe idarea public.aqe_idarea 8 1 54 PPM … -
Django React div with id won't load from js file?
Very new to React + Django The frontend/src/components/App.js: import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class App extends Component { render() { return <h1>React App</h1> } } ReactDOM.render(<App />, document.getElementById('app')); The frontend/src/index.js: import App from './components/App'; Then I have the frontend/templates/frontend/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://bootswatch.com/5/cosmo/bootstrap.min.css"> <title>Lead Manager</title> </head> <body> <div id="app"></div> {% load static %} <script src="{% static "frontend/main.js" %}"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.5/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-kjU+l4N0Yf4ZOJErLsIcvOU2qSb74wXpOhqTvwVx3OElZRweTnQ6d31fXEoRD1Jy" crossorigin="anonymous"></script> </body> </html> When I run the server and go to localhost:8000: The <div id="app"></div> remains empty. No errors raised. I am not sure what the issue might be. I double checked the file against the tutorial I am following. -
python3-saml and Azure AD - missing a point
Good afternoon experts, I have a Django web application (it is not internet-facing) and so far I used the django.contrib.auth.backends.ModelBackend to authenticate the users. However I want to integrate this webapp to an existing SSO solution (like Azure AD) so I thought python3-saml would be a good library to be used (more specifically I use python3-saml-django but it is just a wrapper around python3-saml). Probably I am missing some fundamental point as I don't really understand how this should work. When I used ModelBackend then I had a login form where the user could type their username+password which was checked against Django database and the authentication was completed. Should the same work with SSO too? i.e. the login form appears, the user will type their credentials but they will be checked in Azure AD instead of Django auth tables? Or the custom login form of that specific auth solution (in this case Azure AD -> Microsoft login form) should be displayed...? The LOGIN_URL setting is configured in my Django app so if no user is logged in then automatically my login form appears. Also I set the AUTHENTICATION_BACKENDS setting and it points only to django_saml.backends.SamlUserBAckend. I configured AZure AD (registered … -
Django tailwind custom arbitrary colors not working
I've been using django with django-tailwind to build a website that involves color mixing. I take a bunch of colors from a database and mix them together. This results in new colors that I can't write down in the tailwind config and so I've been trying to use the arbitrary values custom colors from the documentation. The css for the color shows up correctly in my inspector but the color itself doesn't compile. I've also noticed that if I manually enter the color hex anywhere in the code (on another element for example), all elements with that specific color code get rendered correctly so I'm guessing it's something to do with django-tailwind not compiling the colors since they are determined during runtime or something. My django template code is as follows: {% for day_obj in days %} <div class="flex flex-col bg-[{{day_obj.day.color}}]"> and here it is from the chrome inspector But it doesn't work. However, this will render all the elements correctly that have that specific color code: #82e153. Elements that are rendered from before also tend to stick around after I remove the manually-entered-hex-code but usually just stop rendering after a while (I assume due to some sort of caching … -
Django changepassword validators overlap
[][1] used imported PasswordChangeForm , it generates 2 errorlist one from the validators and other from oldpassword error and they overlap https://i.stack.imgur.com/1J2vx.png -
django + S3 doens't work when updating Profile
I am working on a django web app, I wasn't working with S3 before but once I started using it, I can view css js and all static pictures that are located there also the default profile picture of users, Now the problem is users can't upload their profile pictures, once they click update and the page is refreshed their profile picture come back to default one and I lose all informations that has to be updated for profile. this is Profile model: class Profile(models.Model): gender = ( ('Female', 'Female',), ('Male', 'Male',), ) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") first_name = models.CharField(max_length=200,blank=True) last_name = models.CharField(max_length=200,blank=True) username = models.CharField(max_length=200) email = models.EmailField(max_length=200) birthdate = models.DateField(verbose_name=("birthdate"), null=True,blank=True) gender = models.CharField(max_length=60, blank=True, default='',choices=gender,verbose_name="gender") image = models.ImageField(upload_to='static/images/profile_pics/',default='static/images/profile_pics/profile.png',null=True, blank=True) conception = models.ManyToManyField(Conception,related_name="profileconceptions") bio = models.CharField(max_length=100, blank=True,default='') slug = models.SlugField(null=True, blank=True,allow_unicode=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) phoneNumber = PhoneNumberField(null=True, blank=False, unique=True) objects = ProfileManager() def __str__(self): #return f"{self.user.username}-{self.created.strftime('%d-%m-%Y')}" return f'{self.user.username},{self.id}' __initial_first_name = None __initial_last_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__initial_first_name = self.first_name self.__initial_last_name = self.last_name def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) SIZE = 300, 300 if self.image: pic = Image.open(self.image.name) pic.thumbnail(SIZE,Image.LANCZOS) pic.save(self.image.name) if self.slug == None: slug = slugify(self.user.username,allow_unicode=True) has_slug = Profile.objects.filter(slug=slug).exists() … -
Send email and sms django phone auth
I'm using the django-phone-auth library for authentication, but I can't figure out how to send email verification and phone verification # for email from django.dispatch import receiver from phone_auth.signals import verify_email @receiver(verify_email) def verify_email_signal(sender, user, url, email, **kwargs): ... # Send email ... #for phone from django.dispatch import receiver from phone_auth.signals import verify_phone @receiver(verify_phone) def verify_phone_signal(sender, user, url, phone, **kwargs): ... # Send SMS ... the documentation says this. How can i send email and phone ?? please help me )) -
How to change DRF endpoints's required fields
I am using jwt.io on my DRF project. As you know jwt.io has already a Login API view called 'TokenObtainPairView' and it requires 2 fields: username and password. But in our project, we want users to log in with their email instead of their username. I handle this with the following code: class LoginAPIView(TokenObtainPairView): def post(self, request, *args, **kwargs): email=request.data['email'] request.POST._mutable = True profile=ProfileModel.objects.get(email=email) request.data['username']=profile.username request.POST._mutable = False return super().post(request, *args, **kwargs) It works but on my swagger when front-end devs check the endpoint they see that the endpoint requires 2 fields: username and password. But I want them to see required fields such as email and password. here is the how my endpoint look like Is there any way to change its required fields? -
ModuleNotFoundError: No module named 'learning_logs.urls'
I'm working on a Django project from a book right now. The version is a little outdated so I've been trying to follow the documentation for the more up to date version on some things. I'm running into an issue adding the urls. It says: ModuleNotFoundError: No module named 'learning_logs.urls' My urls.py code: from django.contrib import admin from django.urls import path from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls')) ] Is there any other code I need to add? Thanks for any help! -
How to place cursor at end of text in input field after form submission using html and javascript?
I've created a text input form in html that sends user input words via POST method to Django views.py file. Here is the code for this form <form method="POST" action="search"> {% csrf_token %} <input type="search" name="search" value="{{form.search.value}}" placeholder="Search here..." autofocus x-webkit-speech/> </form> The value attribute takes the value returned by Django after a submit. Here is the code of my Django views.py file: from django.shortcuts import render import requests from bs4 import BeautifulSoup as bs from search.models import MyForm def index(request): return render(request, 'index.html') def search(request): if request.method == 'POST': search = request.POST['search'] form = MyForm(request.POST) max_pages_to_scrap = 15 final_result = [] for page_num in range(1, max_pages_to_scrap+1): url = "https://www.ask.com/web?q=" + search + "&qo=pagination&page=" + str(page_num) res = requests.get(url) soup = bs(res.text, 'lxml') result_listings = soup.find_all('div', {'class': 'PartialSearchResults-item'}) for result in result_listings: result_title = result.find(class_='PartialSearchResults-item-title').text result_url = result.find('a').get('href') result_desc = result.find(class_='PartialSearchResults-item-abstract').text final_result.append((result_title, result_url, result_desc)) context = {'final_result': final_result, 'form':form} return render(request, 'index.html', context) else: return render(request, 'index.html') When I submit the form, the value of the input field is well preserved but the cursor goes from the final position to the initial position. To solve this problem, I inserted a javascript script created in this article, in my index.html file … -
_wrapped_view() missing 1 required positional argument: 'request'
below is my code, just trying to include a decorator but getting the above error, have used the decorator elsewhere with no issues. class AudienceListView(ListView): model = Audience template_name = 'audience/list.html' @method_decorator(company_user_has_permission('audiences_view')) def get_queryset(self): queryset = super().get_queryset() company = Company.get_current(self.request) return queryset.filter(company=company) \ .annotate(total_deals=Count("deals"), total_contacts=Count("contacts")) \ .order_by('-id') -
ArrayField in Django model does not validate
My model has an attribute: regione = ArrayField( models.IntegerField( default=0, choices=REGIONE_CHOICES ), blank=True, null=True, default=None ) where REGIONE_CHOICES is ((1, 'opt1'), (2, 'opt2')) and so on. In my ModelForm for my Model I specify a widget for it: class Meta: model = Mymodel fields = [some_fields, 'regione'] widgets = { 'regione': forms.SelectMultiple(choices=REGIONE_CHOICES) } The choices are displayed correctly on the front-end and I can select multiple, but clicking submit doesn't go through, I get Item 1 in the array did not validate as an error in the form. -
Django broken response with file data
In my project I use AWS S3 Bucket for media files. Project contains media_app application, that provide get and post requests to files in remote storage (all requests go through server, so media_app is kinda proxy between frontend and AWS S3. Today I faced with problem. When I try to get media file from AWS S3, Django correctly download it from remote bucket, save it in /tmp/ dir, get correct response metadata, but response itself is broken: it cause infinite response "in progress" state on frontend side (Tried with Postman and Swagger). "In progress" means "frontend application wait until response will be recieved", but on backend side there is no infinite loop. Django can provide next responses even if I use dev test server (Is is means, that no workers are blocked, cause django test server have only one worker). Information about request and response (Django Silk): There is a part of my view, that provide image download: from django.http import Http404, StreamingHttpResponse from wsgiref.util import FileWrapper class ImageDetailAPIView(DetailDownloadAPIView): queryset = Image.objects.filter(is_soft_deleted=False)\ .prefetch_related('thumbnails') serializer_class = ImageSerializer @swagger_auto_schema(responses=image_detail_responses) def get(self, request, *args, **kwargs): try: instance = self.get_object() except Http404: raise FileNotFoundException service = ImageDownloadService(instance) chunk_size = 8192 file_path, status_code = service.download() … -
Why I get error raise ImproperlyConfigured
I want to add info in database using django-seed. seed.py from django_seed import Seed from models import Employee seeder = Seed.seeder() seeder.add_entity(Employee, 5) inserted_pks = seeder.execute() When I try to start command: python3 seed.py I've got this error: Traceback (most recent call last): File "seed.py", line 2, in <module> from models import Employee File "/home/kaucap/test/myproject/app_worker/models.py", line 4, in <module> class Employee(models.Model): File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/db/models/base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 67, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Can anyone explain why I have this error and how I can fix it?