I’m trying to import:
from django.db import models
PyCharm underlines django.db
and complains: Unresolved reference 'django'
.
How do I get PyCharm to recognize Django?
alex
6,8689 gold badges53 silver badges103 bronze badges
asked Feb 9, 2017 at 19:53
2
I assume you’re using a virtualenv which is located in the same directory as other project files. Python should know exactly that path. So, it’s possibly that Pycharm is using the wrong Interpreter.
Go to Settings -> Project: -> Project Interpreter -> switch to the right path
In the interpreter packages, there should be Django package installed. If not, do it here/in terminal.
answered Apr 17, 2017 at 16:58
Mark root folder of project as ‘Sources root’, it works for me.
Content Root
answered Jan 22, 2019 at 11:24
Igor ZIgor Z
6016 silver badges7 bronze badges
4
Above answers are answered partially.
Problem Description: I’ve multiple versions of python installed and Django is installed in one of Python version. There are two issues
-
Issue 1: Pycharm has wrong python interpreter. For this the
Project Interpreter
has to be changed to Python version where Django is installed. Solution: Follow all steps. -
Issue 2: Django isn’t listed as package. For this we need make available the installed python packages in the Pycharm environment. Solution: Follow all steps except step 3.
Solution:
Peform following steps.
- In preference/settings go to
Project
>Project Interpreter
- On right hand side click on
settings icon
>Add Local
- Select correct Python version from
Base Interpreter
- Mark the checkbox against
Inherit global site-packages
andMake available to all projects
- Click
ok
Once this is done in Project Intepreter
you will be able to see Django
in the Package list.
answered Mar 17, 2018 at 6:11
1
If you create the project use python2.7, and in python2.7 path you installed the django, the project works normal. Then you switch the Project Interpreter to the python3.5, but this path did not install the django, then you will get this issue.
answered Aug 8, 2017 at 8:17
aircraftaircraft
25.3k28 gold badges91 silver badges166 bronze badges
I got this problem and it stopped my unit tests from running.
I found that PyCharm, during an upgrade, had set my Python Interpreter
to one which was in a virtual environment, which I do not use any more for this project. So I set it to my global Python environment in C:\Python
and everything works like a charm.
I hope this will help someone.
LuFFy
8,82910 gold badges41 silver badges59 bronze badges
answered Mar 29, 2017 at 18:55
GrahamJGrahamJ
5284 silver badges15 bronze badges
1
if you have installed Django successfully before, in a different location from project location:
in pycharm go to the setting
>Project
>project interpreter
.
right side of the Project Interpreter, click on setting icon and choose add local
.
then in New Environment check these two checkbox:
- inherit global site-packages
- make available to all projects
then press Ok
and Apply
button and wait installing the interpreter to your project location.
LuFFy
8,82910 gold badges41 silver badges59 bronze badges
answered Dec 17, 2017 at 17:43
MiladMilad
832 silver badges8 bronze badges
You can make pyCharm recognize it by setting it to use your virtualenv setup that I assume you had it already for the project
STEP 1: open preferences PyCharm > Preferences
STEP 2: Search for interpreter
and on the right window, select your virtual environment to be used in Project Interpreter
STEP 3 (ADDITIONAL): adding your environment to the list if it didn’t show up
-
select show all interpreter, and then on the pop up window, click + icon on the bottom left
-
select radio button
Existing Environment
and select your virtual env, and then check «Make available for all project» if you use the env for other project, and click ok
STEP 4: On the preferences window, click apply or straight click the ok button. wait couple second and django variable should be available in your project
answered Dec 22, 2018 at 18:15
WindoWindo
1,5261 gold badge12 silver badges8 bronze badges
1
Menu
-> Invalidate Caches / Restart
-> Invalidate and Restrart
answered Sep 3, 2020 at 15:55
Leonid DashkoLeonid Dashko
3,6571 gold badge18 silver badges26 bronze badges
Add this site-packages works for me. (On 20191218, using the newest version of PyCharm ,and python3.7.5 )
answered Dec 18, 2019 at 6:35
MarsYoungMarsYoung
4711 gold badge5 silver badges13 bronze badges
1
I had this problem too. In fact, I faced with this problem because django
package had not been installed in Pycharm. Therefore, I went to this path and clicked on plus sign;then, I searched django
and installed it. It worked well.
file
>setting
>project
>project interpreter
LuFFy
8,82910 gold badges41 silver badges59 bronze badges
answered Jun 2, 2018 at 10:09
M_GhM_Gh
1,0464 gold badges17 silver badges43 bronze badges
I used virtualenv in my project and the following steps is works for me.
Settings -> Project:XXX -> Project Interpreter —> click the right
side icon next to project interpreter -> more -> select the virtualenv
interpreter
hope it can help someone
core114
5,17517 gold badges93 silver badges189 bronze badges
answered Oct 3, 2018 at 3:12
I fix this issue by changing «Project Structure».
Try to unmark parent folder as «Sources»
answered Jun 14, 2018 at 11:21
1
I’m trying to import:
from django.db import models
PyCharm underlines django.db
and complains: Unresolved reference 'django'
.
How do I get PyCharm to recognize Django?
alex
6,8689 gold badges53 silver badges103 bronze badges
asked Feb 9, 2017 at 19:53
2
I assume you’re using a virtualenv which is located in the same directory as other project files. Python should know exactly that path. So, it’s possibly that Pycharm is using the wrong Interpreter.
Go to Settings -> Project: -> Project Interpreter -> switch to the right path
In the interpreter packages, there should be Django package installed. If not, do it here/in terminal.
answered Apr 17, 2017 at 16:58
Mark root folder of project as ‘Sources root’, it works for me.
Content Root
answered Jan 22, 2019 at 11:24
Igor ZIgor Z
6016 silver badges7 bronze badges
4
Above answers are answered partially.
Problem Description: I’ve multiple versions of python installed and Django is installed in one of Python version. There are two issues
-
Issue 1: Pycharm has wrong python interpreter. For this the
Project Interpreter
has to be changed to Python version where Django is installed. Solution: Follow all steps. -
Issue 2: Django isn’t listed as package. For this we need make available the installed python packages in the Pycharm environment. Solution: Follow all steps except step 3.
Solution:
Peform following steps.
- In preference/settings go to
Project
>Project Interpreter
- On right hand side click on
settings icon
>Add Local
- Select correct Python version from
Base Interpreter
- Mark the checkbox against
Inherit global site-packages
andMake available to all projects
- Click
ok
Once this is done in Project Intepreter
you will be able to see Django
in the Package list.
answered Mar 17, 2018 at 6:11
1
If you create the project use python2.7, and in python2.7 path you installed the django, the project works normal. Then you switch the Project Interpreter to the python3.5, but this path did not install the django, then you will get this issue.
answered Aug 8, 2017 at 8:17
aircraftaircraft
25.3k28 gold badges91 silver badges166 bronze badges
I got this problem and it stopped my unit tests from running.
I found that PyCharm, during an upgrade, had set my Python Interpreter
to one which was in a virtual environment, which I do not use any more for this project. So I set it to my global Python environment in C:\Python
and everything works like a charm.
I hope this will help someone.
LuFFy
8,82910 gold badges41 silver badges59 bronze badges
answered Mar 29, 2017 at 18:55
GrahamJGrahamJ
5284 silver badges15 bronze badges
1
if you have installed Django successfully before, in a different location from project location:
in pycharm go to the setting
>Project
>project interpreter
.
right side of the Project Interpreter, click on setting icon and choose add local
.
then in New Environment check these two checkbox:
- inherit global site-packages
- make available to all projects
then press Ok
and Apply
button and wait installing the interpreter to your project location.
LuFFy
8,82910 gold badges41 silver badges59 bronze badges
answered Dec 17, 2017 at 17:43
MiladMilad
832 silver badges8 bronze badges
You can make pyCharm recognize it by setting it to use your virtualenv setup that I assume you had it already for the project
STEP 1: open preferences PyCharm > Preferences
STEP 2: Search for interpreter
and on the right window, select your virtual environment to be used in Project Interpreter
STEP 3 (ADDITIONAL): adding your environment to the list if it didn’t show up
-
select show all interpreter, and then on the pop up window, click + icon on the bottom left
-
select radio button
Existing Environment
and select your virtual env, and then check «Make available for all project» if you use the env for other project, and click ok
STEP 4: On the preferences window, click apply or straight click the ok button. wait couple second and django variable should be available in your project
answered Dec 22, 2018 at 18:15
WindoWindo
1,5261 gold badge12 silver badges8 bronze badges
1
Menu
-> Invalidate Caches / Restart
-> Invalidate and Restrart
answered Sep 3, 2020 at 15:55
Leonid DashkoLeonid Dashko
3,6571 gold badge18 silver badges26 bronze badges
Add this site-packages works for me. (On 20191218, using the newest version of PyCharm ,and python3.7.5 )
answered Dec 18, 2019 at 6:35
MarsYoungMarsYoung
4711 gold badge5 silver badges13 bronze badges
1
I had this problem too. In fact, I faced with this problem because django
package had not been installed in Pycharm. Therefore, I went to this path and clicked on plus sign;then, I searched django
and installed it. It worked well.
file
>setting
>project
>project interpreter
LuFFy
8,82910 gold badges41 silver badges59 bronze badges
answered Jun 2, 2018 at 10:09
M_GhM_Gh
1,0464 gold badges17 silver badges43 bronze badges
I used virtualenv in my project and the following steps is works for me.
Settings -> Project:XXX -> Project Interpreter —> click the right
side icon next to project interpreter -> more -> select the virtualenv
interpreter
hope it can help someone
core114
5,17517 gold badges93 silver badges189 bronze badges
answered Oct 3, 2018 at 3:12
I fix this issue by changing «Project Structure».
Try to unmark parent folder as «Sources»
answered Jun 14, 2018 at 11:21
1
Я пытаюсь импортировать:
from django.db import models
PyCharm подчеркивает django.db
и жалуется: Unresolved reference 'django'
.
Как мне заставить PyCharm узнать Django?
Ответ 1
Я предполагаю, что вы используете virtualenv, который находится в том же каталоге, что и другие файлы проекта. Python должен точно знать этот путь. Таким образом, возможно, что Pycharm использует неверный интерпретатор.
Перейдите в Настройки → Проект: → Переводчик проекта → переключиться на правильный путь
В пакетах интерпретатора должен быть установлен пакет Django. Если нет, сделайте это здесь/в терминале.
Ответ 2
Ответы частично отвечают частично.
Описание проблемы. У меня установлено несколько версий python, а Django — в одной из версий Python. Есть два вопроса
-
Проблема 1: У Pycharm есть неправильный интерпретатор python. Для этого
Project Interpreter
необходимо изменить на версию Python, где установлен Django. Решение. Следуйте всем шагам. -
Проблема 2: Django не указан как пакет. Для этого нам нужно сделать доступными установленные пакеты python в среде Pycharm. Решение. Следуйте всем шагам, кроме шага 3.
Решение:
Выполните следующие шаги.
- В настройках/настройках перейдите к
Project
>Project Interpreter
- В правой части нажмите
settings icon
>Add Local
- Выберите правильную версию Python из
Base Interpreter
- Отметьте флажок напротив
Inherit global site-packages
иMake available to all projects
- Нажмите
ok
Как только это будет сделано в Project Intepreter
, вы сможете увидеть Django
в списке пакетов.
Ответ 3
У меня возникла эта проблема, и она остановила мои модульные тесты.
Я обнаружил, что PyCharm во время обновления установил мой Python Interpreter
на тот, который находился в виртуальной среде, которую я больше не использую для этого проекта. Поэтому я установил его в моей глобальной среде Python в C:\Python
и все работает как шарм.
Надеюсь, это кому-нибудь поможет.
Ответ 4
Если вы создаете проект, используйте python2.7, а в пути python2.7 вы установили django, проект работает нормально. Затем вы переключаете Project Interpreter на python3.5, но этот путь не установил django, тогда вы получите эту проблему.
Ответ 5
если вы успешно установили Django ранее, в другом месте, отличном от местоположения проекта: в pycharm перейдите к setting
> Project
> project interpreter
. В правой части окна «Интерпретатор проекта» щелкните значок настройки и выберите » add local
.
затем в Новой среде установите эти два флажка:
- наследовать глобальные пакеты сайтов
- сделать доступным для всех проектов
затем нажмите кнопку » Ok
и » Apply
и дождитесь установки переводчика в место вашего проекта.
Ответ 6
Вы можете сделать так, чтобы pyCharm распознал его, настроив его на использование вашей установки virtualenv, которая, как я полагаю, у вас уже была для проекта
ШАГ 1: открыть настройки PyCharm > Preferences
ШАГ 2. Найдите interpreter
и в правом окне выберите вашу виртуальную среду для использования в Project Interpreter
ШАГ 3 (ДОПОЛНИТЕЛЬНО): добавление вашей среды в список, если она не отображается
-
выберите Показать всех переводчиков, а затем во всплывающем окне нажмите значок + в левом нижнем углу
-
установите переключатель »
Existing Environment
выберите виртуальный env, а затем установите флажок «Сделать доступным для всех проектов», если вы используете env для другого проекта, и нажмите «ОК».
ШАГ 4: В окне настроек нажмите «Применить» или просто нажмите кнопку «ОК». подождите пару секунд и переменная django должна быть доступна в вашем проекте
Ответ 7
У меня тоже была эта пробема. Фактически я столкнулся с этой проблемой, потому что пакет django
не был установлен в Pycharm. Поэтому я пошел по этому пути и нажал на знак плюс, затем я искал django
и установил его. Это сработало хорошо.
file
> setting
> project
> project interpreter
Ответ 8
Я исправляю эту проблему, изменяя «Структуру проекта». Попробуйте снять отметку с родительской папки как «Источники»
Ответ 9
Я использовал virtualenv в своем проекте, и следующие шаги для меня работают.
Настройки → Проект: XXX → Интерпретатор проекта → щелкните значок справа рядом с переводчиком проекта → еще → выберите переводчика virtualenv
надеюсь, что это может помочь кому-то
Ответ 10
Пометить корневую папку проекта как ‘Sources root’, у меня это работает. Корень контента
10 ответов
Я предполагаю, что вы используете virtualenv, который находится в том же каталоге, что и другие файлы проекта. Python должен точно знать этот путь. Таким образом, возможно, что Pycharm использует неверный интерпретатор.
Перейдите в Настройки → Проект: → Переводчик проекта → переключиться на правильный путь
В пакетах интерпретатора должен быть установлен пакет Django. Если нет, сделайте это здесь/в терминале.
Elisabeth Shevtsova
Поделиться
Ответы частично отвечают частично.
Описание проблемы. У меня установлено несколько версий python, а Django — в одной из версий Python. Есть два вопроса
-
Проблема 1: У Pycharm есть неправильный интерпретатор python. Для этого
Project Interpreter
необходимо изменить на версию Python, где установлен Django. Решение. Следуйте всем шагам. -
Проблема 2: Django не указан как пакет. Для этого нам нужно сделать доступными установленные пакеты python в среде Pycharm. Решение. Следуйте всем шагам, кроме шага 3.
Решение:
Выполните следующие шаги.
- В настройках/настройках перейдите к
Project
>Project Interpreter
- В правой части нажмите
settings icon
>Add Local
- Выберите правильную версию Python из
Base Interpreter
- Отметьте флажок напротив
Inherit global site-packages
иMake available to all projects
- Нажмите
ok
Как только это будет сделано в Project Intepreter
, вы сможете увидеть Django
в списке пакетов.
Ayush Vatsyayan
Поделиться
если вы успешно установили Django ранее, в другом месте, отличном от местоположения проекта: в pycharm перейдите к setting
> Project
> project interpreter
. В правой части окна «Интерпретатор проекта» щелкните значок настройки и выберите » add local
.
затем в Новой среде установите эти два флажка:
- наследовать глобальные пакеты сайтов
- сделать доступным для всех проектов
затем нажмите кнопку » Ok
и » Apply
и дождитесь установки переводчика в место вашего проекта.
Milad
Поделиться
Если вы создаете проект, используйте python2.7, а в пути python2.7 вы установили django, проект работает нормально. Затем вы переключаете Project Interpreter на python3.5, но этот путь не установил django, тогда вы получите эту проблему.
aircraft
Поделиться
У меня возникла эта проблема, и она остановила мои модульные тесты.
Я обнаружил, что PyCharm во время обновления установил мой Python Interpreter
на тот, который находился в виртуальной среде, которую я больше не использую для этого проекта. Поэтому я установил его в моей глобальной среде Python в C:\Python
и все работает как шарм.
Надеюсь, это кому-нибудь поможет.
GrahamJ
Поделиться
Вы можете сделать так, чтобы pyCharm распознал его, настроив его на использование вашей установки virtualenv, которая, как я полагаю, у вас уже была для проекта
ШАГ 1: открыть настройки PyCharm > Preferences
ШАГ 2. Найдите interpreter
и в правом окне выберите вашу виртуальную среду для использования в Project Interpreter
ШАГ 3 (ДОПОЛНИТЕЛЬНО): добавление вашей среды в список, если она не отображается
-
выберите Показать всех переводчиков, а затем во всплывающем окне нажмите значок + в левом нижнем углу
-
установите переключатель »
Existing Environment
выберите виртуальный env, а затем установите флажок «Сделать доступным для всех проектов», если вы используете env для другого проекта, и нажмите «ОК».
ШАГ 4: В окне настроек нажмите «Применить» или просто нажмите кнопку «ОК». подождите пару секунд и переменная django должна быть доступна в вашем проекте
Windo
Поделиться
У меня тоже была эта пробема. Фактически я столкнулся с этой проблемой, потому что пакет django
не был установлен в Pycharm. Поэтому я пошел по этому пути и нажал на знак плюс, затем я искал django
и установил его. Это сработало хорошо.
file
> setting
> project
> project interpreter
M_Gh
Поделиться
Пометить корневую папку проекта как ‘Sources root’, у меня это работает. Корень контента
Igor Z
Поделиться
Я использовал virtualenv в своем проекте, и следующие шаги для меня работают.
Настройки → Проект: XXX → Интерпретатор проекта → щелкните значок справа рядом с переводчиком проекта → еще → выберите переводчика virtualenv
надеюсь, что это может помочь кому-то
user2228903
Поделиться
Я исправляю эту проблему, изменяя «Структуру проекта». Попробуйте снять отметку с родительской папки как «Источники»
Melistraza
Поделиться
Ещё вопросы
- 1C # — XML дочерние узлы в текстовое поле
- 1Как получить доступ к встроенному классу ES6 во встроенном <script>
- 1Vue — Как сохранить поток данных от бабушки и дедушки к внуку?
- 1Использование свойства text = {binding var} для проверки значения введите в элемент управления textbox
- 0MySQL конвертировать строку в дату с миллисекундами
- 0jquery $ .totalStorage — удалить все ключи
- 1Запустите сервис FireBase вручную
- 0Событие FocusChanged в платформе Firebreath
- 1Использование стандартного / выходного потока в качестве строки ввода / вывода
- 1Настройка SFML.net 2.1?
- 1Webscraping с запросами, возвращающими родительскую веб-страницу HTML
- 1Формулы теряются при обновлении строки
- 1Извлечь текст из epub в Python
- 0как отобразить значение в div при нажатии кнопки?
- 0C ++ числа в файле в массив
- 1Как выбрать между различными условиями, зависящими от другой переменной
- 0указатели на многомерные массивы в классе
- 0Подтвердите форму, но при отсутствии ошибок не показывайте поля
- 0MySQL UPDATE запрос не работает с PHP
- 0Перемещение строки таблицы td данных вверх и вниз, за исключением первого td этой строки, для изменения порядка данных
- 1Как узнать, играет ли звук с помощью C #?
- 0Как mysqli_fetch_row при использовании mysqli_multi_query
- 0MySQL на проблемах чувствительности к регистру Ubuntu
- 0Оператор перегрузки >>
- 0Google Map API не загружается, когда скрипт на той же HTML-странице
- 1Tomcat Виртуальный хост и Wildcard DNS соответствия
- 0Массив проверки кода Jquery равен нулю или нет
- 1NullPointerException в Java в списке массивов
- 1RoutingMissingException с использованием NEST IndexMany <>
- 0Показать / скрыть div в DataList с помощью Jquery
- 0Python Mysql Query Cache и использовать его позже для соединения
- 1Можем ли мы использовать базу данных Realm бесплатно как альтернативу Sqlite и CoreData?
- 0Как я могу загрузить файлы CoffeeScript из пакетов Bower с помощью веб-пакета?
- 0Нахождение ранга булевой матрицы
- 0Событие щелчка в плагине листовки — Как заставить событие щелчка работать только внутри изображения мозаики карты?
- 1Как можно увеличить размер значков на вкладке Элементы?
- 1Java nullPointerException при заполнении объекта Hierarchy с помощью saxParser
- 1изменить размер изображения по площади
- 0Угловой JS ngclick в ngrepeat не работает
- 0Перейти автоматически на другую страницу, используя HTML
- 0Показать страницу просмотра с результатами группы из контроллера
- 0как выбрать таблицу по метке th с помощью jquery
- 1Firebase Username / Password Authentication — разрешить вход только одному устройству одновременно
- 0AngularJS Valdiation не работает с директивой People Picker
- 1Пандейские рассуждения о способе условного обновления нового значения из других значений в той же строке в DataFrame
- 1Восстанавливаемое веб-задание Azure (не удалять из очереди)
- 0Где мне нужно развернуть файлы приложения после входа в openshift с помощью filezila
- 0C ++ Маркировка объектов для удаления в списке STD через nullptrs
- 1Запрограммируйте архитектуру нейронной сети с несколькими входами с помощью Keras
- 0Как я могу изменить массив в директиве, а затем отразить это изменение в моем контроллере?
Before fixing the unresolved reference issues, we must know why these issues occur in the first place.
An unresolved reference issue is raised in PyCharm IDE when:
- A variable is called/used outside the scope of its existence.
- A package is used within the code without prior installation or installed with an improper version.
- A function/class used within the code without importing it in the code or has an improper import path.
PyCharm highlights these areas where the code has the issue. Hover the mouse cursor over the highlighted area and PyCharm will display an Unresolved reference.
Let’s see some of the example scenarios of how the Unresolved reference issue occurs.
Issue 1: Using variables out of scope.
Unresolved reference: Variable out of scope
Fix: Declare the variable globally or use it only within the scope.
Fixed: Variable out-of-scope reference issue
Issue 2: Importing a package that has not been installed or does not have the required version containing that function/class.
Unresolved reference: package not installed
Fix: Install the package manually via the command line or click Install package <package-name> in the suggestion box. PyCharm will fetch and install the globally available packages in the current environment.
pip install flask
Fixed: Package installed to resolve the reference
Issue 3: Using a function that has not been imported properly in the current Python file.
File: other.py with hello() function
Unresolved reference: path to function is incorrect
Fix: Correct the line of import with the actual path to the hello() function.
Fixed: Unresolved function import
Disabling the warning altogether
You can also disable the Unresolved references warning completely by following these steps:
- Click on the File option in PyCharm’s menu bar.
File option
- Click on Settings.
Settings
- In the right pane of Settings go to Editor > Inspections.
Python drop-down
- Look for the Unresolved references option in the dropdown list and deselect the checkbox.
Deselect Unresolved references
- Click Apply button and PyCharm will disable showing the Unresolved references warning altogether.
Apply the changes
This is a part of PyCharm’s code Inspection feature, using which programmers can foresee the areas of code which may cause an issue during execution. PyCharm also suggests a quick resolution to most of these issues. This improves the agility of coding along with fewer errors.
Tip: Place the caret where the issue is and press the Alt+Enter shortcut to see the suggested fixes by PyCharm.
Last Updated :
30 Dec, 2022
Like Article
Save Article