Django : Unable to import model from another App - django

I was hoping to seek some assistance on this problem I'm having. I'm still learning Django (and Python) and come across this particular issue that I'm unable to locate an answer for. I've created a new App called "News" and setup the Model for the App. Using the Admin interface I have created some data. From my "Pages" App, I'm trying to import the News_Article class and getting the error No module named News.models.
I am struggling to see what's going wrong here.
Any assistance would be greatly appreciated.
DIR Structure
Bolton_GC [Folder]
- Bolton_GC [Folder]
- News [Folder]
- Migrations [Folder]
- __init__.py
- __init__.pyc
- admin.py
- admin.pyc
- models.py
- models.pyc
- tests.py
- views.py
- Pages [Folder]
- Migrations [Folder]
- __init__.py
- __init__.pyc
- admin.py
- admin.pyc
- models.py
- models.pyc
- tests.py
- views.py
- views.pyc
- static [Folder]
- templates [Folder]
- __init__.py
- __init__.pyc
- settings.py
- settings.pyc
- urls.py
- urls.pyc
- wsgi.py
- wsgi.pyc
- db.sqlite3
- manage.py
news\model.py
from django.db import models
from datetime import datetime
class News_Article(models.Model):
class Meta:
ordering = ['news_datetime_submitted']
news_title = models.CharField(max_length=75, verbose_name="News Title")
news_text = models.CharField(max_length=300, verbose_name="News Text")
news_active = models.BooleanField(default=True, verbose_name="News Active")
news_datetime_submitted = models.DateTimeField(default=datetime.now(), verbose_name="News Date")
def __str__(self):
return self.news_title
Pages\views.py
from django.shortcuts import HttpResponse, get_object_or_404, render
from models import Page, Announcement, Menu, Sub_Menu
from django.core.exceptions import ObjectDoesNotExist
from News.models import News_Article
import pdb
# Helper Functions
def get_announcement():
try:
return Announcement.objects.get(announcement_active=True)
except ObjectDoesNotExist:
return None
def clean_url(dirtyurl, badlist):
for item in badlist:
dirtyurl = dirtyurl.replace(item,'')
return dirtyurl[1:-1]
# View functions
def page(request):
rDict = {}
path = clean_url(request.path, ['"', "'"])
# pdb.set_trace()
p = get_object_or_404(Page, urlconf_text=path)
rDict['p'] = p
announcement = get_announcement()
if not announcement == None:
rDict['announcement'] = announcement
rDict['sitenav'] = path
rDict['menu'] = Menu.objects.all().order_by('menu_position')
return render(request, 'en/public/page.html', rDict)
Error
ImportError at /home/
No module named News.models
Request Method: GET
Request URL: http://127.0.0.1:8000/home/
Django Version: 1.8.2
Exception Type: ImportError
Exception Value:
No module named News.models
Exception Location: C:\Me\Websites\Bolton_GC\Bolton_GC\Pages\views.py in <module>, line 4
Python Executable: c:\python27\python.exe
Python Version: 2.7.9
Python Path:
['C:\\Me\\Websites\\Bolton_GC',
'c:\\python27\\lib\\site-packages\\setuptools-18.0.1-py2.7.egg',
'C:\\WINDOWS\\SYSTEM32\\python27.zip',
'c:\\python27\\DLLs',
'c:\\python27\\lib',
'c:\\python27\\lib\\plat-win',
'c:\\python27\\lib\\lib-tk',
'c:\\python27',
'c:\\python27\\lib\\site-packages']
Server time: Tue, 14 Jul 2015 13:21:14 +0100

Switch
from News.models import News_Article
to
from Bolton_GC.News.models import News_Article

Just to elaborate on #TheLifeOfSteve's answer, all the import statements are always relative to your manage.py file.
If the manage.py file was at the path Bolton_GC/Bolton_GC, then the correct import statement would just be:
from News.models import News_Article
But in the current directory structure, the following is the correct answer as pointed out by Steve.
from Bolton_GC.News.models import News_Article

There is an update in Importing and registering Models!!
Please try from .models import News_Article

Related

Run spiders in the background every n minutes when django server is running

I have a django project. Inside this project, there are some crawlers that crawl data from some websites and store it in database. With the django, these crawled data is shown.
This is the structure of project:
-prj
db.sqlite3
manage.py
-prj
__init__.py
settings.py
urls.py
wsgi.py
-prj_app
__init__.py
prj_spider.py
admin.py
apps.py
models.py
runner.py
urls.py
views.py
I want to run all spiders in the background every 5 minutes when django server is running. In the views.py I have import runner.py and in the runner.py all spiders start crawling.
views.py:
from . import runner
runner.py:
from twisted.internet import reactor
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from multiprocessing import Process, Queue
from .prj_spider import PrjSpider
from background_task import background
#background()
def run_spider(spider):
def f(q):
try:
configure_logging()
runner = CrawlerRunner()
deferred = runner.crawl(spider)
deferred.addBoth(lambda _: reactor.stop())
reactor.run()
q.put(None)
except Exception as e:
q.put(e)
q = Queue()
p = Process(target=f, args=(q,))
p.start()
result = q.get()
p.join()
if result is not None:
raise result
for spider in spiders:
run_spider(DivarSpider, repeat=60)
When run the server, I get this error:
TypeError: Object of type type is not JSON serializable
Also with this type of runner.py, I get below error:
runner.py:
#background()
def fetch_data():
runner = CrawlerRunner()
runner.crawl(PrjSpider)
d = runner.join()
d.addBoth(lambda _: reactor.stop())
reactor.run()
fetch_data(repeat=60)
error:
raise error.ReactorNotRestartable() twisted.internet.error.ReactorNotRestartable

Django Model Import Error: ValueError: attempted relative import beyond top-level package

I have created a new app "grn" in my django project and tried to import the models from another app named "packsapp" in the same project like this:
Models.py
from ..packsapp.models import *
But I got the following error:
ValueError: attempted relative import beyond top-level package
Here's the structure of the app:
yantra_packs
grn
--migrations
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
media
packsapp
--migrations
templates
templatetags
views1
__init__.py
apps.py
decorators.py
forms.py
models.py
urls.py
views.py
How can I import the models of the packsapp in the grn ??
The root directory of a Django project is not a Python package or module. So relative imports across Django apps will not work. Use an absolute import instead:
from packsapp.models import *

django-comments add a new url and a view for comments?

i am newer and study django.when i install django_comments , i need add to add a new url and view for django_comments, but it don't work.
comments folder structure:
__init__.py __pycache__/ forms.py migrations/ models.py templates/ urls.py views.py
__init__.py:
def get_model():
from comments.models import CommentModel
return CommentModel
def get_form():
from comments.forms import CommentForm
return CommentForm
and forms.py and models.py is fine work.but when i add urls.py, views.py and add the urls to main urls file. it don't work.
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('delete/<int:comment_id>/', views.delete_own_comment, 'delete_own_comment'),
]
views.py
from .models import CommentModel
#login_required
def delete_own_comment(request, comment_id):
comment = get_object_or_404(CommentModel, id=comment_id, site__pk=settings.SITE_ID)
if comment.user == request.user:
comment.is_removed = True
comment.save()
but when i add path('mycomments/', include('comments.urls')) to main urls.py, it run strange errors. can anyone help me???
It's not
django-admin startapp myapp
It's
python manage.py startapp myapp
Provided that you created before a project with
django-admin startproject myproject

A Schema is required to be provided to GraphQLView

I was following this tutorial to integrate Graphql with Django, I did everything according to that tutorial when I'm hitting graphql URL on my local machine
http://localhost:8000/graphql
I'm geting the following error
AssertionError at /graphql
A Schema is required to be provided to GraphQLView.
Request Method: GET
Request URL: http://localhost:8000/graphql
Django Version: 1.11.1
Exception Type: AssertionError
Exception Value:
A Schema is required to be provided to GraphQLView.
Exception Location: /home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages/graphene_django/views.py in init, line 84
Python Executable: /home/psingh/Projects/django_graphql/env/bin/python
Python Version: 2.7.6
Python Path:
['/home/psingh/Projects/django_graphql/project',
'/home/psingh/Projects/django_graphql/env/lib/python2.7',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/plat-x86_64-linux-gnu',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-tk',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-old',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/site-packages']
Server time: Fri, 12 May 2017 12:18:31 +0000
In settings.py
GRAPHENE = {
'SCHEMA': 'project.schema.schema'
}
project> schema.py
import graphene
import mainapp.schema
class Query(mainapp.schema.Query, graphene.ObjectType):
# This class will inherit from multiple Queries
# as we begin to add more apps to our project
pass
schema = graphene.Schema(query=Query)
app>schema.py
import graphene
from graphene_django.types import DjangoObjectType
from cookbook.ingredients.models import Category, Ingredient
class CategoryType(DjangoObjectType):
class Meta:
model = Category
class IngredientType(DjangoObjectType):
class Meta:
model = Ingredient
class Query(graphene.AbstractType):
all_categories = graphene.List(CategoryType)
all_ingredients = graphene.List(IngredientType)
def resolve_all_categories(self, args, context, info):
return Category.objects.all()
def resolve_all_ingredients(self, args, context, info):
# We can easily optimize query count in the resolve method
return Ingredient.objects.select_related('category').all()
project_urls.py
from django.conf.urls import include, url
from django.contrib import admin
from graphene_django.views import GraphQLView
import schema
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql', GraphQLView.as_view(graphiql=True)),
url(r'^', include('mainapp.urls')),
]
Any help would be great.I am new to the coding stuff.
Thanks in advance.
You have to add the schema to your settings.py as seen here:
GRAPHENE = {
'SCHEMA': 'cookbook.schema.schema'
}
You need 2 schema.py files, one at the root level of the project and one in the app folder.
if you don't want to add GRAPHENE variable in settings.py then you can pass scheme parameter in GraphQLView.as_view() method call
from onlineshop_project.scheme import schema
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql', GraphQLView.as_view(graphiql=True, schema=schema)),
]
You can check the documentation.
Have you added "graphene_django" in INSTALLED_APPS under settings.py file ?
Check here - https://docs.graphene-python.org/projects/django/en/latest/tutorial-plain/#update-settings

django templatedoesnotexist current_date

I'm going through the Django Book. I'm in the middle of Chapter 4. I can't render my current_datetime.html template view. What am I doing wrong? It looks like the template loaders are not finding the right directory. http://www.djangobook.com/en/2.0/chapter04/
I have created my templates directory in my project folder and current_datetime.html with in the directory.
Setting.py
import os.path
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
# I've also tried: # '/Users/macuser/Python_Projects/django_test1/templates',
)
views.py
from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})
urls.py
from django.conf.urls import patterns, include, url
from django_test1.views import hello, my_homepage_view, current_datetime, hours_ahead
urlpatterns = patterns('',
(r'^$', my_homepage_view),
(r'^hello/$', hello),
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),)
The error:
TemplateDoesNotExist at /time/
current_datetime.html
Request Method: GET
Request URL:
Django Version: 1.4
Exception Type: TemplateDoesNotExist
Exception Value:
current_datetime.html
Exception Location: /Library/Python/2.7/site-packages/django/template/loader.py in find_template, line 138
Python Executable: /usr/bin/python
Python Version: 2.7.1
Python Path:
['/Users/macuser/Python_Projects/django_test1',
'/Library/Python/2.7/site-packages/distribute-0.6.27-py2.7.egg',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
'/Library/Python/2.7/site-packages']
Server time: Mon, 23 Jul 2012 20:40:35 -0500
Template-loader postmortem
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/Library/Python/2.7/site-packages/django/contrib/auth/templates/current_datetime.html (File does not exist)
You havn't checked render_to_Response format
https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response
Go through it, You need to add context_instance=RequestContext(request) to the response
This was a silly mistake. I did not create an actual app: python manage.py startapp "appName". I put "assert False" in the settings file and realized django was not even using my settings.py file.