Could not import app.models in view file - python

First django app and am having a bit of trouble my project is laid out like this
MyProject
-dinners (python package, my app)
-views (python package)
__init__.py
dinners.py(conflict was here... why didn't I add this to the q.. sigh)
general.py
__init__.py
admin.py
models.py
tests.py
views.py
-Standard django project boilerplate
In my /views/general.py file it looks like this:
import os
import re
from django.http import HttpResponse
from django.template import Context,loader
from dinners.models import Dinner
def home(request):
first_page_dinners = Dinner.objects.all().order_by('-created_at')[:5]
t = loader.get_template('general/home.html')
c = Context({
'dinners':first_page_dinners,
})
return HttpResponse(t.render(Context()))
And in my urls.py file I have this regular expression to map to this view
url(r'^/*$','dinners.views.general.home', name="home")
However when I try to hit the home page I get this error:
Could not import dinners.views.general. Error was: No module named models
Removing the dinners.models import at the top of general.py (plus all of the model specific code) removes the error. Am I somehow importing incorrectly into the view file? Naturally I need to be able to access my models from within the view...
Thanks
UPDATE: answer I had a file dinners.py within the -views package that was conflicting

You need to put a __init__.py file in "dinners" and "views" folder to make those valid packages.
EDIT:
Also, remove that views.py file, that will create conflict with the package.

Related

How do I correctly import models in Python if I'm having such directories?

I'm using Django-REST framework with a telegram-bot in here. I need to import models from Django inside my telegram-bot file. I'm getting module not found error and probably thinking something wrong. Telegram-bot file is commands.py and the django models is models.py. The whole project looks like this:
Project directories
I just want to properly import models inside my commands.py file
Here is the possible solution for your question..
add following code inside my commands.py file
import sys
from django.apps import apps
from django.conf import settings
settings.configure(INSTALLED_APPS=['app_name'])
apps.populate(settings.INSTALLED_APPS)
from app_name.models import YourModel
also you may need to update path.
import sys
sys.path.append('path/to/your/django/project')
As you mentioned, You are using Django REST Framework, so you should try with a serializer file. import your model in serializer file, because the syntax is correct 'from app_name.models import YourModel'. Moreover, instead of settings.configure(INSTALLED_APPS=['app_name']) try this in settings.py
file in INSTALLED_APPS = 'app_name.apps.AppNameConfig'.

Issues with Importing python files within a Django Project

I'm having problems with importing python files within my project. I've clearly set up a file named testing.py within a folder called api, which is the same directory where my views.py file. When I import testing within views.py, I keep getting an error: "ModuleNotFoundError: No module named 'testing'". I'm not sure if I need to create an init.py file here for the module, but it should be importing without any error regardless. Can anyone help me figure out this issue?
views.py file within api:
import http
from django.shortcuts import render
from django.shortcuts import HttpResponse
import testing
# Create your views here.
def test(request) :
return HttpResponse(testing.testFunction())
testing.py file within api:
def testFunction():
return "This is a test"
If it is in your API folder, it should be from api.testing import testFunction

importing models inside django application

I have made an app inside my django application. I'm trying to create a file(testabc.py) in the same directory as views.py and I want to import models in that file.
The name of model is "Example"
Now, in views.py, I import models in the following way:
from .models import Example
a = Example.objects.get()
Here, I am getting proper output
However, in my testabc.py file when I write the same code
I get the following error
from .models import Example
ValueError: Attempted relative import in non-package
You need to add file __init__.py in your folder.
Here is the doc for python module.

Can't import Django model into scrapy project

I have a folder Project which contains Django project called djangodb and Scrapy project called scrapyspider.
So it looks like:
Project
djangodb
djangodb
myapp
scrapyspider
scrapyspider
spiders
items.py
scrapy.cfg
__init__.py
I want to import model Product from myapp app in items.py
The problem is that it returns import error:
from Project.djangodb.myapp.models import Product as MyAppProduct
ImportError: No module named djangodb.myapp.models
Tried many things but couldn't avoid this error. Do you have ideas?
Your problem is that you're trying to do an import from a file that's outside from Django schema, to solve that you can overwrite the sys.pathvar which includes locations as the actual dir, so you can change it to:
import sys
sys.path.insert(0, 'C:\\Users\\your_path\\Project')
sys.path.insert(0, '/path/to/application/Project/') # Linux
# And then import #
from djangodb.myapp.models import Product as MyAppProduct

Unresolved reference 'models'

I am writing custom template tag, and the error occurs that "Unresolved reference 'models'"
the following is my blog_tags.py.
from django import template
from .models import Post
register = template.Library()
#register.simple_tag
def total_posts():
return Post.published.count()
And my directory tree is as followed
blog/
__init__.py
models.py
...
templatetags/
__init__.py
blog_tags.py
And i do have a Post class in my Models.
And when i click the prompt by pycharm "install package Post", after finishing installed it, the error disappear.
I wonder do i have to do the same, which is install the package by the IDE, every time when i want to write a custom tag evolved with class in my Models?
If I'm interpreting your project structure correctly, your models module is located in a parent package relative to blog_tags. Accessing .models would try to find the module inside your templatetags package.
Try to change your import to this instead:
from ..models import Post
As this is Django and as in Django circular imports can be an issue, consider dynamically loading the model:
for django 1.7+ use the application registry:
from django.apps import apps
Post = apps.get_model('blog', 'Post')
for earlier versions:
from django.db.models.loading import get_model
Post = get_model('blog', 'Post')
Note: This only works if 'blog' is an installed app.
import your models with app namespace instead of relative import, so that the standard structure is maintained.
from django import template
# blog is your app name
from blog.models import Post
register = template.Library()
#register.simple_tag
def total_posts():
return Post.published.count()
Please check here unresolved error issue related to pycharm in django projects

Categories