Django Application: Model ImportError - python

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.

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.

Automatically import custom files in Django

I have a Django project containing some files which are, obviously, not automatically discovered by Django. My workaround is to import them in urls.py so that Django can see them. This is how my urls.py looks like:
from django.contrib import admin
from django.urls import path
from custom_file_1 import * # "unused" import
from custom_file_2 import * # "unused" import
urlpatterns = [
...
]
My IDE considers the commented imports unused, since they are not used, but they are vital so that Django can process those files.
And the question: is there any nice way to let Django see those files? And how to do that?
It is usually not a good idea to import things with wildcards. Imagine that in one of the custom files some object with the name path is present, then it will override the reference to the path function you imported from django.urls.
Usually one imports such files (that for example contain signals, etc.) in the AppConfig.
In the directory of the app, there is an __init__.py file. You can write
# app/__init__.py
default_app_config = 'app.config.CustomAppConfig'
In your app directory, you then define the config of your app:
# app/config.py
from django.apps import AppConfig
class CustomAppConfig(AppConfig):
name = 'app'
def ready(self):
import custom_file_1 # noqa
import custom_file_2 # noqa
Here # noqa is used to ignore the flake8 warnings.

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'

Python recognize classes as modules in import

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 !

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

Categories

Resources