Python recognize classes as modules in import - python

I have a Django app with following structure:
my_app
--models
----__init__.py
----MyModelClass.py
--utils
----__init__.py
----MyBase.py
--admin.py
--urls.py
My models __init__.py file contains:
from .MyModelClass import MyModelClass # noqa
My utils __init__.py file contains:
from .MyBase import MyBase # noqa
Then when I tried to import MyModelClass in MyBase file with this:
from ..models import MyModelClass
or this:
from apps.my_app.models import MyModelClass
I got module instead of class. And then I should use:
MyModelClass.MyModelClass.objects.all()
P.S And even I got error when tried with this:
from ..models.MyModelClass import MyModelClass
P.P.S I have a serializes folder with similar folder structure in app where I store Serializer classes for Django Rest Framework. And in MyModelClassSerializer.py:
from ..models import MyModelClass
class MyModelClassSerializer(serializers.ModelSerializer):
class Meta:
model = MyModelClass
works as expected !

Related

ModuleNotFoundError: No module named 'music_controller.api'

When I run the server, I am getting the following error:
from music_controller.api.models import Room
ModuleNotFoundError: No module named 'music_controller.api'
I think the problem is from the import in the views.py:
from django.shortcuts import render
from rest_framework import generics
from .serializers import RoomSerializer
from .models import Room
# Create your views here.
class RoomView(generics.CreateAPIView):
queryset = Room.objects.all()
serializer_class = RoomSerializer
I made sure that the app name is included in INSTALLED_APPS in the settings.py.
The following is the tree of my project:
In the music_controller directory, add a file called __init__.py. Leave the file empty.

Apps not loaded yet when using actstream django

So i'm trying to create an application for user interaction with stream_django. So far everything was going well until I got error:
'User model not registered. Please register model with actstream.registry'.
So after searching for some time, I modified my apps.py to be like this:
The project is called reviews
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reviews.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "reviews.settings"
django.setup()
from django.apps import AppConfig
from django.contrib.auth.models import User
class MyappConfig(AppConfig):
name = 'myapp'
def ready(self):
from actstream import registry
registry.register(User,self.get_model('Post'),self.get_model('UserProfile'))
But now I'm getting error:
'AppRegistryNotReady("Apps aren't loaded yet")'
I'm not sure what to do anymore, any help is appreciated.
I faced the same problem but I found that the solution was to add the default_app_config setting in the __init__.py of your main project (same location as your settings.py).
For your case, that __init__.py file should look like this:
# reviews/__init__.py
default_app_config = 'myapp.apps.MyappConfig'

apps/goods/models.py 'apps.goods.models' apps is not package?

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?
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
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

Django Application: Model ImportError

I have a django 1.9 application using DRF with the following folder structure
- api/
- api/models.py
- api/serializers.py
- api/views.py
- manage.py
In serializers.py I have an import:
from api.models import Model1, Model2, ...
In views.py I have these imports:
from api.serializers import NotificationSerializer
from api.models import Model1, Model2, ...
Everything works fine until now. But after adding
from api.serializers import NotificationSerializer
in models.py, django starts complaining when I start the dev server:
File ".../api/serializers.py", line 3, in <module>
from api.models import Model1, Model2,...
ImportError: cannot import name Model1
I know that there must be a problem with the python import paths, but I can't figure it out.
This would cause a circular import, since serializers.py imports models.py, and vise versa.
How to resolve this depends on what NotificationSerializer does. If it does not use the models, you might consider moving it to a utils file.

Importing Views

My app layout
my_app
__init__.py
my_app
__init__.py
startup
create_app.py
create_users.py
common_settings.py
core
models.py
views.py
Inner __init__.py
from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__) # The WSGI compliant web application object
db = SQLAlchemy(app) # Setup Flask-SQLAlchemy
manager = Manager(app) # Setup Flask-Script
from my_app.startup.create_app import create_app
create_app()
create_app.py
from native_linguist_server import app, db
#app.before_first_request
def initialize_app_on_first_request():
""" Create users and roles tables on first HTTP request """
from .create_users import create_users
create_users()
def create_app(extra_config_settings={}):
app.config.from_envvar('ENV_SETTINGS_FILE')
# Load all blueprints with their manager commands, models and views
from my_app import core
return app
When I run my app like this and try to load a view in my browser, I get a 404 error.
However if I change:
from my_app import core
to
from my_app.core import views
it works fine.
Could someone please explain to me the difference between these two calls? I would have thought from my_app import core would also import views.py and hence there wouldn't be an issue.
Thank you.
from my_app import core
will load and execute my_app/core/__init__.py (if it exists). You will then have access to any identifiers defined inside or imported into __init__.py.
from my_app.core import views
will load and execute my_app/core/views.py. You'll then have access to any identifiers defined inside or imported into views.py.
To get the behavior you're expecting, you'll need to import views inside __init__.py:
from . import views

Categories

Resources