I wonder why I get this error :
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.
this is my code :
from main_app.models import student
std1 = student(name='tom', fullname='scholz')
std1.save()
print(student.objects.all())
there is not any problem with running server and migrations. but when it comes to running a .py file (made by myself) such an error rises.
CodePudding user response:
This problem is simply because Django doesn't know where to find required settings. As it's [Documentation][1] mentions :
When you use Django, you have to tell it which settings you’re using. Do this
by using an environment variable, DJANGO_SETTINGS_MODULE.
based on Documentation you should do that (informing Django about the setting)by defining a environmental variable.
as I see that there are little ambiguities about what to do facing this error a list of different solutions you can take, is provided :
1- define a environment variable in the operating system([link][2]).
2- if you are using a virtual environment; set a new environment variable in activate.bat
set "DJANGO_SETTINGS_MODULE=<your_proj_name>.settings"
in this way, whenever you activate the virtual environment that variable would be defined automatically.
3- (the way you did!)in each python file; write the command which defines that environment variable.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<your_proj_name>.settings')
but if you use the third method, it is really important where you are putting that command(in the second and definitely first case we don't care at all!). so you should take care of not using Django before that command in your script. (some people wonder why after using this command still we are getting the same error. the reason is they put that line of code in a place where Django was used before)
you might ask why when you were using migration and so on; you didn't face this error. the reason would be clear if we take a look at manage.py because there is that command there(third method of the above list)
but you [1]: https://docs.djangoproject.com/en/4.0/topics/settings/#designating-the-settings [2]: https://www.computerhope.com/issues/ch000549.htm