Django is not importable in this environment ошибка

I’m getting the following errors in Pycharm.

Error: Django is not importable in this environment

It used to work well but I moved the project and virtualenv to a different directory and the error appeared. It’s weird because if I run the project ignoring the configuration settings warning, it works fine.

The problem is that now, Pycharm is not finding the project interpreter.

The command that Pycharm is running is:

/Users/plorenzo/../gestorSchools/venv/bin/python3.4 /Users/plorenzo/../gestorSchools/schoolsManager/manage.py runserver 8000

The virtualenv is activated.

My $PATH is:

/Users/plorenzo/../gestorSchools/venv/bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin

and my $PYTHONPATH:

/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4

I spent a few days trying to find the solution but I couldn’t find it.

Dave Mackey's user avatar

Dave Mackey

4,28621 gold badges78 silver badges136 bronze badges

asked Dec 8, 2014 at 17:38

Pablo L's user avatar

4

Yet another case, where my virtualenv did have Django installed, but Pycharm would still display this error.

I eventually found out that the same virtualenv path had been duplicated in the list of available interpreters. Removing all of them and re-adding fixed it.

The duplication happened after I copied the .idea from another machine, and re-created the virtualenv from Pycharm although it was already listed as a (broken) interpreter.

answered Feb 27, 2018 at 10:38

Arnaud P's user avatar

Arnaud PArnaud P

11.9k7 gold badges56 silver badges67 bronze badges

5

In my case I had to go to Settings (Alt+F7, or the Spanner/Cog icon) and select a Python interpreter which has Django installed alongside it.

If Django isn’t already installed, you should be able to install it via the + (plus) icon (not shown below) once an interpreter has been selected.

enter image description here

answered Sep 28, 2015 at 10:15

James Bradbury's user avatar

James BradburyJames Bradbury

1,6781 gold badge19 silver badges31 bronze badges

For people having selected a virtualenv/interpreter that HAS Django installed (but it might have changed python version since first selection…), and even re-installed Django, and still get this message, and slowly getting crazy:

File > Invalidate Caches / Restart ...

Also, keeping the list of available interpreters clean and correct always helps (on my linux, old interpreters of previous linux installations kept popping up…whaat), as well as not using special characters in virtualenv names (as was the OPs problem…see his answer). Messing with the .idea folder also is not recommended (dont copy it to your new computer ;-).

answered Sep 7, 2019 at 8:24

benzkji's user avatar

benzkjibenzkji

1,68620 silver badges41 bronze badges

4

Project interpreter, which is being used in the pycharm setting , doesn’t have the django package installed. So go to

setting->Project->project interpreter

Then install django package

it will work :)

Machavity's user avatar

Machavity

30.7k27 gold badges91 silver badges100 bronze badges

answered Jan 11, 2016 at 20:17

Siyaram Malav's user avatar

Siyaram MalavSiyaram Malav

4,3462 gold badges31 silver badges31 bronze badges

1

I finally found the error. The problem was that one folder name in the virtualenv path had an accent.

This is the old path:

/Users/plorenzo/../telefónica/gestorSchools/venv

This is the new one that works:

/Users/plorenzo/../telefonica/gestorSchools/venv

answered Dec 8, 2014 at 20:14

Pablo L's user avatar

Pablo LPablo L

1,2661 gold badge12 silver badges25 bronze badges

2

I had the same problem and it was due to having more than one project interpreter defined in the project. In my case I had a python 2.7 and a python 3.7 interpreter. Fixed this issue by removing the python 2.7 interpreter.

  1. View the current interpreter by navigating to Preferences > Project > Project Interpreter

  2. Open the dropdown and select Show All...

  3. Remove any interpreters that aren’t your primary

answered Nov 26, 2018 at 19:31

biodynamiccoffee's user avatar

It might seem obvious, but try quitting and then re-starting the PyCharm application. When I had this issue, I continued to get the «Django is not importable in this environment» error even though the project interpreter path was correct. Nothing worked until I closed and re-opened the application. Hope this saves someone some time.

answered Oct 25, 2017 at 19:10

g.carey's user avatar

g.careyg.carey

6909 silver badges6 bronze badges

1

I got the same issue on OS X, and to fix it, I had to use an absolute path for the project interpreter

/Users/myself/Projects/… is ok
~/Projects/… was not working

answered Dec 23, 2014 at 14:38

cbueche's user avatar

I had the same problem and I think the solution is not stated here yet. I had to go to Settings > Project Interpreter, click the gears icon on the right and chose the interpreter (which was already correct). Then click on the last icon to the right, the one with some folders structure icon. There I had to add the path to the site-packages of my venv (where Django is). Finally my tests run with no issues.

answered Jun 21, 2019 at 6:36

filias's user avatar

filiasfilias

2442 silver badges9 bronze badges

1

I had similar problem…

I go PyCharm -> Preferences and tried to readd Django to project interpreter packages. PyCharm suddenly added everything in requirements.txt file. And now I can run project without any problem.

answered Jan 14, 2015 at 21:59

tanaydin's user avatar

tanaydintanaydin

5,15228 silver badges45 bronze badges

In my case, I was running the Cygwin version of Python when this error came up. Fixing it involved just adding some of cygwin’s bin paths to Window’s Path variable.

Run «control sysdm.cpl»
Go to the «Advanced» tab
Click the «Environmental Variables» button at the bottom of this tab
Find «Path» under «System Variables»
Add to it
;c:/cygwin/bin;c:/cygwin/sbin;c:/cygwin/usr/local/bin

I did not include /usr/bin, as for some reason, it is combined in to the /bin directory when viewing in windows.

answered Feb 9, 2016 at 10:16

Dakusan's user avatar

DakusanDakusan

6,4644 gold badges32 silver badges45 bronze badges

Ok, in my case the solution was:

  1. Install django
  2. Use @cbueche suggestion to remove the ~
  3. Switch to a another project’s venv and switch back to my venv for this project

I exited and reloaded the project a few times in there so that might also be necessary. I love PyCharm but starting a new project is always painful.

answered Jan 13, 2017 at 16:57

Rob Osborne's user avatar

Rob OsborneRob Osborne

4,8674 gold badges31 silver badges43 bronze badges

1

As everybody said ,Check for your interpreter
Was it properly configured it or not.If you created your project in virtual environment ,make sure you configured the correct python interpreter or not .The python interpreter(whole) and python interpreter(for only single project using virtualenv) are different .

If you are using PyCharm
Go to Setting->Project->project interpreter and pick the right interpreter
Once you are done with that ,run the project if it runs,all set .if not check for the Edit configurations and check again for the interpreterenter image description here

answered Jan 24, 2017 at 5:12

Trinadh Koya's user avatar

Trinadh KoyaTrinadh Koya

1,08915 silver badges19 bronze badges

I had the same problem in Pycharm.

I fixed it by removing the old Run/Debug Configurations and then create another one.

Before that make sure to install Django if you haven’t already.

It is better to clear caches by going File > Invalidate Caches / Restart ... to be more sure.

answered Jul 16, 2022 at 7:48

Olive Hair's user avatar

Olive HairOlive Hair

3,63125 silver badges30 bronze badges

you have to edit your project configuration for that.
Environemt->Environment variables set varable DJANGO_SETTINGS_MODULE=project_name.settings

answered May 3, 2018 at 18:25

Nids Barthwal's user avatar

I kept getting this error even after following suggestions made in other answers, like deleting .idea folder, reinstalling packages from settings->project interpreter.

Finally, I took the venv out of the project folder and created a venev beside the project folder and deleted .idea folder from project folder.

Then I opened the project and chose the interpreter as the newly created venv

answered Jul 7, 2020 at 8:21

Vivek Singh's user avatar

Vivek SinghVivek Singh

3263 silver badges14 bronze badges

steps :

 1. Choose File Option
 2. Setting
 3. Scroll to Project -> Select Python Interpreter
 4. Project Interpreter
 5. Click on Setting icon and press Add environment
 6. Create a Virtual Environment

answered Oct 24, 2020 at 3:03

Abi Chhetri's user avatar

Abi ChhetriAbi Chhetri

1,0519 silver badges15 bronze badges

I had the same error. Try to name path (and project) without «_»:

../my_project/venv -> ../my-project/venv

answered Jan 20, 2021 at 21:59

DIlyaY's user avatar

1 Everybody recommend you to check your Interpreter PATH to your venv-folder (virtual environment) in PyCharm:
Settings (Ctrl+Alt+S) —> Project: project_name —> Python Interpreter —> gear_icon (settings) —> Show All… —> press ‘+’ to add interpreter with correct path to venv —> Apply —> Ok

2 I also recommend you to try my kung-foo AFTER you done previous:
same steps… —> Show All… —> press ‘folder-tree icon’ (Show paths for the selected interpreter) —> press ‘+’ to add new path —> select path to this folder ‘../venv/Lib/site-packages’

Do that and you’ll be extra-happy!

answered Oct 22, 2021 at 11:40

valentin's user avatar

1

Есть проект, который запускается через manage.py runserver, но при попытке запуска через pycharm открывает конфиг дебага, где внизу пишет, что нельзя импортировать джангу в этом окружении. Как исправить?


  • Вопрос задан

    более трёх лет назад

  • 5839 просмотров

Django is not importable in this environment.
(1) the first thing to illustrate the point, now on the network all kinds of copy, about today I encountered this problem, didn’t find a good way to online, and open a, then open a, completely identical copy, was no, really is too sad, to solve the problem it took me 4 to 5 hours (I am a rookie!
If this article does not obtain my consent, do not reprint and plagiarism!
(2) PyCharm downloaded from the Internet or copied from other computers cannot be opened directly, and some Settings need to be made, which is very annoying! Of course, the main problem is to set up the interpreter, but there are other problems, such as Django is not importable in this environment. My software version is python3.4.3 and django 2.0.7
(3) Solutions to this problem:
The file – & gt; Open, find your project file (project name), as follows, my project file is under the Learn folder, which has 4 projects

Then look at the following:
Select open in the new window to open a new window. Select another window to close the one you are currently open.

My entire project list is as follows:

It doesn’t matter that my project name is not the same as zaxt_tMP12 under the project.
And then: file – & gt; Settings – & gt; Project Interpreter

Then, look at the picture:

Hide interpreters that connect to other projects:

The effect is as follows, then green + :

If it’s OK, the result is like this (don’t follow it here, I’m just showing you!! :

Django is not importable in this environment if you don’t grab Inherit global site-packages, you will get an error when you run.



Very distressed! ?You’ve been messing with me for a long time. In fact, here’s what you should do:

Then, apply – & gt; ok

Django is out!!
(4) Finally, add an interpreter:

Select the interpreter we set up in the previous step! And run manager.py Runserver. Click Run again and you’re ready to run!

It took quite a while to write the document, redid it and liked it if it helped.
If this article does not obtain my consent, do not reprint and plagiarism!

Read More:

Solution 1

I finally found the error. The problem was that one folder name in the virtualenv path had an accent.

This is the old path:

/Users/plorenzo/../telefónica/gestorSchools/venv

This is the new one that works:

/Users/plorenzo/../telefonica/gestorSchools/venv

Solution 2

Yet another case, where my virtualenv did have Django installed, but Pycharm would still display this error.

I eventually found out that the same virtualenv path had been duplicated in the list of available interpreters. Removing all of them and re-adding fixed it.

The duplication happened after I copied the .idea from another machine, and re-created the virtualenv from Pycharm although it was already listed as a (broken) interpreter.

Solution 3

In my case I had to go to Settings (Alt+F7, or the Spanner/Cog icon) and select a Python interpreter which has Django installed alongside it.

If Django isn’t already installed, you should be able to install it via the + (plus) icon (not shown below) once an interpreter has been selected.

enter image description here

Solution 4

For people having selected a virtualenv/interpreter that HAS Django installed (but it might have changed python version since first selection…), and even re-installed Django, and still get this message, and slowly getting crazy:

File > Invalidate Caches / Restart ...

Also, keeping the list of available interpreters clean and correct always helps (on my linux, old interpreters of previous linux installations kept popping up…whaat), as well as not using special characters in virtualenv names (as was the OPs problem…see his answer).

Solution 5

Project interpreter, which is being used in the pycharm setting , doesn’t have the django package installed. So go to

setting->Project->project interpreter

Then install django package

it will work :)

Comments

  • I’m getting the following errors in Pycharm.

    Error: Django is not importable in this environment

    It used to work well but I moved the project and virtualenv to other directory and the error appeared. It’s weird because if I run the project ignoring the configuration settings warning that I get, works fine.

    The problem is that now, Pycharm is not finding the project interperter.

    The command that Pycharm is running is:

    /Users/plorenzo/../gestorSchools/venv/bin/python3.4 /Users/plorenzo/../gestorSchools/schoolsManager/manage.py runserver 8000
    

    The virtualenv is activated.

    My $PATH is:

    /Users/plorenzo/../gestorSchools/venv/bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
    

    and my $PYTHONPATH:

    /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4
    

    I spent a few days trying to find the solution but I couldn’t find it.

  • Thank you! This is what was causing the issue for me, too

  • in setting->Project->project interpreter I saw the Django package, but installing it again solved the problem for me

  • Thank you. Just restarting PyCharm solved the issue for me.

  • I had to remove the .idea folder, but didn’t see the same virtualenv path, so not sure why i kept getting this.

  • After a quick experiment: when opening the interpreter settings from inside a freshly created project, Pycharm still suggests the virtualenvs from my other projects. So I am tempted to conclude that the ‘interpreter’ data is stored somewhere more central. Eg. on linux I’ve got stuff in ~/.PyCharm2019.1. Although this somewhat contradicts my own answer :p

  • Restarting Pycharm makes sense. What just now worked for me was uninstalling and reinstalling Django.

  • fun fact: you get all the upvotes, for a problem that was not yours, but that many others have!

  • Solved it for me, PyCharm 2019.3.1 (Professional Edition) Build #PY-193.5662.61, built on December 18, 2019

  • Wow, I tried all 15 suggestions above here with no success, but this one finally worked!

  • Saved me a lot of head scratching just now, thank you!

  • Worked for me too, was driving me nuts with a false positive error. PyCharm 2016.3.2 Build #PY-163.10154.50, built on December 28, 2016

  • This problem is really hard to spot if spanish is your native tongue.

  • Thanks! Exact my issue after I recreated the virtual env for the new version of python but with the same name as was before.

  • Work for me while using a docker image. PyCharm 2020.3.3 (Professional Edition) Build #PY-203.7148.72

  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

  • looks like this issue is still experienced in…2021…

Recents

Related

Я получаю следующие ошибки в Pycharm.

Ошибка: Django не импортируется в этой среде

Он работал хорошо, но я переместил проект и virtualenv в другой каталог, и появилась ошибка. Это странно, потому что, если я запускаю проект, игнорируя предупреждение о настройках конфигурации, которое я получаю, работает нормально.

Проблема в том, что теперь Pycharm не находит межпроцессора проекта.

Команда, которую выполняет Pycharm:

/Users/plorenzo/../gestorSchools/venv/bin/python3.4 /Users/plorenzo/../gestorSchools/schoolsManager/manage.py runserver 8000

Виртуализован активирован.

My $PATH:

/Users/plorenzo/../gestorSchools/venv/bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin

и my $PYTHONPATH:

/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4

Я потратил несколько дней, пытаясь найти решение, но я не смог его найти.

4b9b3361

Ответ 1

Наконец-то я нашел ошибку. Проблема заключалась в том, что одно имя папки в виртуальном пути имело акцент.

Это старый путь:

/Users/plorenzo/../telefónica/gestorSchools/venv

Это новый, который работает:

/Users/plorenzo/../telefonica/gestorSchools/venv

Ответ 2

В моем случае мне нужно было перейти к настройкам (Alt + F7 или значок Spanner/Cog) и выбрать интерпретатор Python с установленным Django рядом с ним.

Если Django еще не установлен, вы можете установить его с помощью значка «зеленый +» (не показано ниже) после выбора интерпретатора.

введите описание изображения здесь

Ответ 3

Еще один случай, когда на моем virtualenv был установлен Django, но Pycharm все равно отображал эту ошибку.

В конце концов я обнаружил, что тот же путь virtualenv был продублирован в списке доступных переводчиков. Удаление всех из них и повторное добавление исправили это.

Дублирование произошло после того, как я скопировал .idea с другой машины и воссоздал virtualenv из Pycharm, хотя он уже был указан как (сломанный) интерпретатор.

Ответ 4

У интерпретатора проекта, который используется в настройке pycharm, не установлен пакет django. Итак, перейдите к

setting->Project->project interpreter

Затем установите пакет django

он будет работать:)

Ответ 5

Это может показаться очевидным, но попробуйте выйти, а затем снова запустить приложение PyCharm. Когда у меня возникла эта проблема, я продолжал получать ошибку «Django не является импортируемой в этой среде», хотя путь интерпретатора проекта был правильным. Ничего не работало, пока я не закрыл и не открыл приложение. Надеюсь, что это кому-то поможет.

Ответ 6

У меня такая же проблема на OS X, и для ее исправления мне пришлось использовать абсолютный путь для интерпретатора проекта

/Пользователи/сам/Проекты/… в порядке
~/Projects/… не работает

Ответ 7

У меня была та же проблема, и это было связано с тем, что в проекте было определено более одного интерпретатора проекта. В моем случае у меня был Python 2.7 и интерпретатор Python 3.7. Исправлена эта проблема путем удаления интерпретатора Python 2.7.

  1. Просмотрите текущий интерпретатор, перейдя в » Preferences > Project > Project Interpreter

  2. Откройте раскрывающийся список и выберите Show All...

  3. Удалите переводчиков, которые не являются вашими основными

Ответ 8

У меня была схожая проблема…

Я отправляю PyCharm → Preferences и пытался прочитать Django для создания пакетов интерпретатора. PyCharm неожиданно добавила все в файл requirements.txt. И теперь я могу запускать проект без проблем.

Ответ 9

В моем случае я запускал версию Cygwin Python, когда эта ошибка возникла. Исправление связано с добавлением некоторых путей bin cygwin к переменной Window Path.

Запустить «control sysdm.cpl»
Перейдите на вкладку «Дополнительно»
Нажмите кнопку «Экологические переменные» в нижней части этой вкладки.
Найдите «Путь» в разделе «Системные переменные»
Добавить к нему
;c:/cygwin/bin;c:/cygwin/sbin;c:/cygwin/usr/local/bin

Я не включил /usr/bin, так как по какой-то причине он объединяется в каталог /bin при просмотре в окнах.

Ответ 10

Хорошо, в моем случае решение было:

  • Установить django
  • Используйте предложение @cbueche для удаления ~
  • Переключитесь на другой проект venv и вернитесь к моему вену для этого проекта.

Я выходил и перезагружал проект несколько раз там, чтобы это также было необходимо. Мне нравится PyCharm, но начинать новый проект всегда тяжело.

Ответ 11

Как сказали все, проверьте свой интерпретатор
Правильно ли он настроен или нет. Если вы создали свой проект в виртуальной среде, убедитесь, что вы настроили правильный интерпретатор python или нет. Интерпретатор python (полный) и интерпретатор python (только для одного проекта, использующего virtualenv) разные.

Если вы используете PyCharm
Перейдите в Настройка- > Проект- > проект и выберите правильный интерпретатор
Как только вы закончите с этим, запустите проект, если он запустится, все настроены .if не проверять конфигурацию редактирования и снова проверить интерпретатор введите описание изображения здесь

Ответ 12

Для людей, которые выбрали virtualenv/интерпретатор, который установил и даже переустановил HAS django, и все еще получают это сообщение, и постепенно сходят с ума: нажмите File > Invalidate Caches / Restart ....

Это решило это для меня.

Ответ 13

Вы должны изменить конфигурацию вашего проекта для этого. Environemt-> Переменные окружения установлены как переменные DJANGO_SETTINGS_MODULE = имя_проекта .settings

Ответ 14

У меня была такая же проблема, и я думаю, что решение здесь еще не указано. Мне нужно было перейти в «Настройки»> «Интерпретатор проекта», щелкнуть значок шестеренки справа и выбрать переводчика (что уже было правильно). Затем нажмите на последний значок справа, значок со структурой некоторых папок. Там я должен был добавить путь к пакетам сайта моего venv (где находится Django). Наконец, мои тесты запускаются без проблем.

Ответ 15

установить Django решить мои проблемы

  • Divinity original sin 2 ошибки прошлого карон сбежал
  • Divxmediaserver exe системная ошибка
  • Divizion by zero ошибка sql
  • Divinity original sin 2 ошибки прошлого карон не появляется
  • Divinity original sin 2 ошибка сохранения 503