Django Testing in PyCharm. manage

I have a simple django project that I'm making in pycharm. The directory structure is the following:

zelda_botw_cooking_simulator
|-- cooking_simulator_project
|---- manage.py
|---- botw_cooking_simulator   # django app
|------ init.py
|------ logic.py
|------ tests.py
|------ all_ingredients.py
|------ other standard django app files
|---- cooking_simulator_project  # django project

When I run python manage.py test in the PyCharm terminal, everything works great.

When I click the little triangle icon in PyCharm next to a test to run that test, however, I get an error saying:

File ".../zelda_botw_cooking_simulator/cooking_simulator_proj/botw_cooking_simulator/tests.py", line 5, in <module>
    from .all_ingredients import all_ingredients
ImportError: attempted relative import with no known parent package

How can I fix this?

I have tried configuring run environments and test environments in PyCharm for 30 minutes now and I'm not getting it. The questions/answers here and here are close, but there's not quite enough detail for me to fix it. Exactly what do I put in each field in each window? What's the 'target', the 'working directory', do I need an environment variable? What goes in the settings part and what goes in the configuration? ChatGPT recommended a bunch of stuff that didn't work. Thank you!

There are only 2 possibilities of this error:

  1. Either there is no environment variable or not configured correctly
  2. The path of the all_ingredients is relative try changing it to absolute, change from .all_ingredients import all_ingredients to from botw_cooking_simulator.all_ingredients import all_ingredients

I would highly prefer to try and check for the second solution. You can also examine the error:

File ".../zelda_botw_cooking_simulator/cooking_simulator_proj/botw_cooking_simulator/tests.py", line 5, in <module>
    from .all_ingredients import all_ingredients
ImportError: attempted relative import with no known parent package

which is also pointing towards the same thing:

ImportError: attempted relative import with no known parent package

Figured it out! The problem lay in how PyCharm was interpreting the test. The question and answer here was super helpful, but I had to do the opposite and add a working directory:

  1. Replace from django.test import TestCase with from unittest import TestCase in my tests.py file.

  2. Add the working directory to the templates. Note I had to update the autodetect template, not only the unittest template:

First: select Edit Configurations from the Run menu Make sure to select 'Edit Configuration Templates', don't just update one.

Second: select autodetect within the Python tests menu option. Python tests autodetect Then update the working directory to be the one with your manage.py file in it.

Now the little green buttons work!

Back to Top