0

my project directories is:

apps/
    goods/
        models.py
        views.py
        base.py
    trades/
    users/
    __init__.py

apps/goods/base.py

from django.views.generic.base import View

from apps.goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]
        for good in goods:
            # json_dict = {}
            # json_dict['name'] = good.name
            # json_dict['category'] = good.category.name
            # json_dict['market_price'] = good.market_price
            # json_dict['add_time'] = good.add_time
            # json_list.append(json_dict)

            from django.forms.models import model_to_dict

            for good in goods:
                json_dict = model_to_dict(good)
                json_list.append(json_dict)

            from django.http import HttpResponse
            import json
            return HttpResponse(json.dumps(json_list), content_type='application/json')

i'm debug base.py not get data, but get the error:

from apps.goods.models import Goods
ModuleNotFoundError: No module named 'apps.goods'; 'apps' is not a package

and, i remove 'apps' in 'apps.goods.models', get the error:

from goods.models import Goods
ModuleNotFoundError: No module named 'goods'

env:

 pycharm-2017.2

 django-1.11.6

why get the error?

mmy
  • 67
  • 1
  • 13

2 Answers2

1

Use just from .models import Goods (look at "." before models - it means the module is from current folder ).Because base.py and models.py are in same folder (same app) so you dont need to specify from which app you want to import models. Just simply include it like this.

But if you want to import models from other apps, you should to make apps to be package.
In Goods app folder add __init__.py.
Structure should look like:

apps/
    goods/
        __init__.py     
        models.py
        views.py
        base.py
    trades/
    users/
    __init__.py

Than use from goods.models import Goods or from apps.goods.models import Goods

FirePower
  • 424
  • 4
  • 13
  • use from.models import goods get error:__main__.modules,main is not package – mmy Oct 25 '17 at 09:54
  • Show me models.py code. And be carefull you need to import Goods - class (big G) not goods - variable in view. – FirePower Oct 25 '17 at 10:04
  • Ok, I know path of models. I wanted to see code in models. Did you try to import Goods from django shell? That is my way to check/debug imports in my projects. – FirePower Oct 25 '17 at 12:10
0

As in the others' comments, you need to create the init file in the folder that should be considered a package. It's called __init__.py however. You have one of these files in apps, make sure you have it in apps/goods as well.

If you still have the same problem, make sure your configuration in Django is correct, i.e. the folder above apps is loaded

Elias Mi
  • 611
  • 6
  • 14