I have a problem importing a model from another app. I am using Django 2.0
.
My project structure looks like this:
--api
--api
--settings.py
--urls.py
--wsgi.py
--product
--models.py
--chat
--models.py
--manage.py
To show only the problem I have I simplified the structure. If you are missing something important let me know it.
The file causing the error:
chat/models.py
from api.product.models import Product
from django.contrib.auth.models import User
from django.db import models
class Chat(models.Model):
product = models.ForeignKey(Product)
enquirer = models.ForeignKey(User)
product/models.py
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, related_name='category', on_delete=None)
front_image = models.ImageField(upload_to="")
title = models.CharField(max_length=100)
price = models.PositiveIntegerField()
description = models.CharField(max_length=5000)
date = models.DateTimeField(auto_now_add=True)
settings.py
INSTALLED_APPS = [
'account.apps.AccountConfig',
'product.apps.ProductConfig',
'profileInfo.apps.ProfileInfoConfig',
'chat.apps.ChatConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
]
The error is the following: ModuleNotFoundError: No module named 'api.product'
I do not understand why Django even can not find api.product
.
Is that a common problem ? Thank you for your help.
To do this, create a directory called /«project»/«app_name»/models , inside it put __init__.py (to declare it as a module) and then create your files inside there. You then need to import your file contents into the module in __init__.py . You should read about Python modules to understand this.
Based on your settings and the file directory, the project root is the uppest app
directory. So that means that you import the models by writing:
from product.models import Product
instead of:
from api.product.models import Product
If your IDE suggested that import, something is probably wrong with the project root.
The solution I found that works for me using Python 3.x
...
from django.apps import apps
...
and then whereever in your code you need to import a model you can do the following....
model = apps.get_model('app_name', 'ModelName')
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With