ImportError: cannot import name 'BookList' - django

This a relative import error that got me crazy.
Here below is the directory tree and code:
books
├── admin.py
├── apps.py
├── forms.py
├── __init__.py
├── models.py
├── tests.py
├── urls.py
└── views.py
models.py
from django.db import models from django.core.urlresolvers import reverse
from . import views
class BookList(models.Model):
cover = models.ImageField(upload_to='cover/%Y/%m/%d')
# cover = models.CharField(max_length=200, blank=False)
title = models.CharField(max_length=100, blank=False)
author = models.CharField(max_length=50)
publisher = models.CharField(max_length=50)
review = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse(views.detail_book, kwargs={'id': self.id})
views.py (The code crashed at the line below pdb.set_trace())
import pdb
from django.views import generic
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
pdb.set_trace()
from .models import BookList
from .forms import BookListForm
class BookRecommend(generic.ListView):
model = BookList
template_name = 'books/books_list.html'
context_object_name = 'books'
paginate_by = 1
def add_book(request):
if request.method == 'POST':
form = BookListForm(request.POST)
if form.is_valid():
book = form.save()
return HttpResponseRedirect(reverse(detail_book, kwargs={id: book.id}))
else:
form = BookListForm()
return render(request, 'books/add_book.html', {'form': form})
def delete_book(request):
pass
def modify_book(request):
pass
def detail_book(request, id=1):
book = get_object_or_404(BookList, id=id)
return render(request, 'books/detail_book.html', {'book': book})
Trace back:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0xb621a2fc>
Traceback (most recent call last):
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/home/michael/Envs/DJ19/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/michael/Envs/DJ19/Profile/books/models.py", line 4, in <module>
from . import views
File "/home/michael/Envs/DJ19/Profile/books/views.py", line 9, in <module>
from .models import BookList
ImportError: cannot import name 'BookList'
There no obstacle at the previous version before i add some view functions.
Thanks in advance!

Related

Can't identify problem in my serializers.py file

I can't figure out why I'm getting errors. If I don't import the serializers.py file then the error goes (my views don't yet make use of this file).
Serializers.py:
from rest_framework import serializers
# This file is the equivilent of forms.py in that we define models to serialise.
class MerchantSerializer(serializers.Serializer):
id = serializers.CharField(required=True, max_length=50)
name = serializers.CharField(required=True, max_length=100)
logo = serializers.URLField(max_length=250, required=False)
class DataSerializer(serializers.Serializer):
account_id = serializers.CharField(required=True, max_length=50)
amount = serializers.IntegerField(required=True, min_value=0)
created = serializers.DateTimeField()
currency = serializers.CharField(required=True, max_length=3)
description = serializers.CharField(required=True, max_length=250)
id = serializers.CharField(required=True, max_length=50)
category = serializers.CharField(required=True, max_length=100)
is_load = serializers.BooleanField()
settled = serializers.DateTimeField()
merchant = serializers.ListField(child=MerchantSerializer)
class TransactionSerializer(serializers.Serializer):
type = serializers.CharField(required=True, max_length=50)
data = serializers.ListField(child=DataSerializer)
My view isn't doing anything yet. Plan was to just receive some JSon to create my webhook, validate the JSON and then save the data. The JSON contains objects that span several models and the field names won't match the models so I don't think I can use any model serializers.
Views.py:
from django.shortcuts import render
from django.contrib.auth.models import User
from rest_framework import viewsets
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
import datetime
from .models import Transaction
from .serializers import TransactionSerializer
#Enable logging
import logging
logger = logging.getLogger(__name__)
# Create your views here.
#csrf_exempt
def index(request):
data = json.loads(request.body)
return render(request, 'template.html', )
Traceback:
python manage.py runserver 80
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\philip\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\philip\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = self._run_checks(
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\urls\resolvers.py", line 407, in check
for pattern in self.url_patterns:
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\philip\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\philip\CodeRepos\MonzoWebHook\monzowebhook\urls.py", line 6, in <module>
import core.views
File "C:\Users\philip\CodeRepos\MonzoWebHook\core\views.py", line 9, in
<module>
from .serializers import TransactionSerializer
File "C:\Users\philip\CodeRepos\MonzoWebHook\core\serializers.py", line
10, in <module>
class DataSerializer(serializers.Serializer):
File "C:\Users\philip\CodeRepos\MonzoWebHook\core\serializers.py", line
20, in DataSerializer
merchant = serializers.ListField(child=MerchantSerializer)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\rest_framework\fields.py", line 1646, in __init__
assert not inspect.isclass(self.child), '`child` has not been instantiated.'
AssertionError: `child` has not been instantiated.
You need to add parantheses after setting childs.
data = serializers.ListField(child=DataSerializer())
merchant = serializers.ListField(child=MerchantSerializer())

Django Rest Framework Module Not Found Error

I made sure that every step was followed correctly but this happened and I don't know how to solve this.
**ERROR:**
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000017F5090E620>
Traceback (most recent call last):
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\management\base.py", line 379, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\management\base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Chrisannesuuuu\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Chrisannesuuuu\etona\etona\etona\urls.py", line 3, in <module>
import etona.quickstart.views
ModuleNotFoundError: No module named 'etona.quickstart'
urls.py
from django.urls import include, path
from rest_framework import routers
import etona.quickstart.views
router = routers.DefaultRouter()
router.register(r'users', etona.quickstart.views.UserViewSet)
router.register(r'groups', etona.quickstart.views.GroupViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from etona.quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
when typing python manage.py runserver, the error above appeared. How can i fix it? help please. Im trying to run the djangorestframework and connect it to angular to have a simple registration , so i followed the instructions on this website https://www.django-rest-framework.org/tutorial/quickstart/ but it doesn't seem to work on me. Maybe I missed something. Please help. Thanks.
Use quickstart.views instead of import etona.quickstart.views in urls.py and views.py
use in views.py change this line
from etona.quickstart.serializers import UserSerializer, GroupSerializer
to
from quickstart.serializers import UserSerializer, GroupSerializer
urls.py -from
etona.quickstart import views
to
from quickstart import views

Django Rest Framework AttributeError 'function' object has no attribute 'model' in router.register

I try my first Django API using Django Rest Framework. Everything was fine, but I change something and stuck in this AttributeError and don't understand what to do. my code looks like in tutorial and it is half past 4 am, I really need help.
so,
this is the callback
python3 manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute
self.check()
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/dev/test/demo/api_demo/api_demo/urls.py", line 7, in <module>
router.register(r'developers', views.DevViewSet)
File "/home/dev/test/demo/lib/python3.5/site-packages/rest_framework/routers.py", line 72, in register
base_name = self.get_default_base_name(viewset)
File "/home/dev/test/demo/lib/python3.5/site-packages/rest_framework/routers.py", line 152, in get_default_base_name
return queryset.model._meta.object_name.lower()
AttributeError: 'function' object has no attribute 'model'
this is url.py file
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from developers import views
router = routers.DefaultRouter()
router.register(r'developers', views.DevViewSet)
urlpatterns = [
url(r'^admin', admin.site.urls),
url(r'^api_demo', include(router.urls)),
]
this is views.py
from rest_framework.viewsets import ModelViewSet
from developers.models import Developers
from .serializers import DevSerializer
class DevViewSet(ModelViewSet):
queryset = Developers.objects.all
serializer_class = DevSerializer
and serializer
from rest_framework import serializers
from .models import Developers
class DevSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Developers
fields = ('name', 'surname', 'skills', 'education', 'employment_history')
and models
from django.db import models
class Education(models.Model):
university = models.CharField(max_length=50)
year_of_graduation = models.DateField()
class Empl_history(models.Model):
company = models.CharField(max_length=50)
role = models.CharField(max_length=30)
fr = models.DateField(verbose_name='from')
to = models.DateField()
class Developers(models.Model):
name = models.CharField(max_length=50)
surname = models.CharField(max_length=30)
skills = models.ForeignKey('Skills', on_delete=models.CASCADE)
education = models.ManyToManyField(Education)
employment_history = models.ManyToManyField(Empl_history)
class Skills(models.Model):
SKILLS_CHOICES = (
('p', 'Python'),
('d', 'Django'),
('drf', 'Django Rest Framework'),
)
skills_choices = models.CharField(max_length=2, choices=SKILLS_CHOICES,)
and in settings I added this 'rest_framework' and 'developers' to INSTALLED_APPS, also I add this code in the end
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'PAGE_SIZE': 10
}
Will be very thankfull for any advice and critic
For the queryset declaration you need to call the function and return the QuerySet rather then pass the reference to the function e.g. change queryset = Developers.objects.all to queryset = Developers.objects.all()
from rest_framework.viewsets import ModelViewSet
from developers.models import Developers
from .serializers import DevSerializer
class DevViewSet(ModelViewSet):
queryset = Developers.objects.all()
serializer_class = DevSerializer
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from developers import views
router = routers.DefaultRouter()
router.register(r'developers', views.DevViewSet)
urlpatterns = [
url(r'^admin', admin.site.urls),
url(r'', include(router.urls)),
]

not able to use anaconda packages in django app

I m new in python web development. I m using Django framework but i also need machine learning libraries so after installing django and working on it for a while i have installed anaconda distribution of python and i have directed my interpreter in pycharm to anaconda. The problem is when i import libraries like sklearn or pandas and then i run server, it gives me that error in command prompt
PS C:\Users\xxx\desktop\intelligent> python manage.py runserver
Performing system checks...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03C62780>
Traceback (most recent call last):
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\utils\a
utoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ma
nagement\commands\runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ma
nagement\base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ma
nagement\base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ch
ecks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ch
ecks\urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ch
ecks\urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\utils\f
unctional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\urls\re
solvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\utils\f
unctional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\urls\re
solvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\xxx\desktop\intelligent\intelligent\urls.py", line 24, in <module>
url(r'^$', include('home.urls')),
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\conf\ur
ls\__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\xxx\desktop\intelligent\home\urls.py", line 3, in <module>
from . import views
File "C:\Users\xxx\desktop\intelligent\home\views.py", line 14, in <module>
import pandas
ModuleNotFoundError: No module named 'pandas'
My setting.py file is unchanged. If i try to import libraries like sklearn without using django then it is running fine but in django app it gives above error even if the interpreter is set to anaconda in pycharm. I don't know if view.py file is useful or not but here it is
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader
from django.shortcuts import redirect
from django.contrib.auth import authenticate,login
from django.views import generic
from django.views.generic import View
from .signupForm import UserForm
from .signinform import SignInForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
import pandas
# Create your views here.
#login_required(login_url='signin')
def index(request):
context = {'app':'app'}
return render(request,'home/index.html',context)
def signup(request):
context = {'app':'app'}
return render(request,'home/signup.html',context)
def signupform(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('index.html')
else:
form = UserForm()
return render(request, 'home/signup.html', {'form': form})
def signinform(request):
if request.method == 'POST':
#form = SignInForm(request.POST)
username = request.POST['username']
raw_password = request.POST['password']
user = authenticate(username=username, password=raw_password)
if user is not None:
login(request, user)
return redirect('index.html')
else:
form = SignInForm()
return render(request, 'home/signin.html')
def logoutview(request):
logout(request)
return redirect('../signin')
def diagnosis(request):
# result = main("8 1 3 100 150 1 2 77 1 1 2 2 3")
context = {'app': 'app'}
return render(request, 'home/diagnosis.html', context)
According to the logs the module pandas is missing.
File "C:\Users\xxx\desktop\intelligent\home\views.py", line 14, in <module>
import pandas
ModuleNotFoundError: No module named 'pandas'
You have to install it, with pip for example :
pip install pandas

ImportError: cannot import name 'Comment' django 1.9

I am new in django.
I have two app named comments and newapp.I am trying to import one of Class (Comment Class) from comments app to newapp. But I get an error called
ImportError: cannot import name 'Comment'
Here is my 'model.py' from comments app
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
# Create your models here.
from newapp.models import NewApp
from newapp.models import Test
class CommentManager(models.Manager):
def filter_by_instance(self, instance):
content_type = ContentType.objects.get_for_model(instance.__class__)
obj_id = instance.id
qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id)
return qs
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
#post = models.ForeignKey(NewApp)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()
def __unicode__(self):
return str(self.user.username)
def __str__(self):
return str(self.user.username)
Here is the 'model.py' code for newapp app
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.text import slugify
#here is the problem code to import below class
from comments.models import Comment
# Create your models here.
class NewApp(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
image = models.FileField(null=True, blank=True)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def _unicode_(self):
return self.title
def _str_(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug":self.slug})
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
# #property
# def comments(self):
# instance = self
# qs = Comment.objects.filter_by_instance(instance)
# return qs
class Test(models.Model):
def _unicode_(self):
return self.title
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = NewApp.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=NewApp)
INSTALLED APP from setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts',
'comments',
'newapp',
]
And finnaly i got error like this
Unhandled exception in thread started by <function check_errors.<locals>.wrapper
at 0x039B27C8>
Traceback (most recent call last):
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\importlib\__i
nit__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\eXp\Desktop\venv\mysite\comments\models.py", line 8, in <module
>
from newapp.models import NewApp
File "C:\Users\eXp\Desktop\venv\mysite\newapp\models.py", line 13, in <module>
import django.comments
ImportError: No module named 'django.comments'
Unhandled exception in thread started by <function check_errors.<locals>.wrapper
at 0x034627C8>
Traceback (most recent call last):
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\importlib\__i
nit__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\eXp\Desktop\venv\mysite\comments\models.py", line 8, in <module
>
from newapp.models import NewApp
File "C:\Users\eXp\Desktop\venv\mysite\newapp\models.py", line 14, in <module>
from comments.models import Comment
ImportError: cannot import name 'Comment'
You're importing newapp from comments and comments from newapp. In python, you can't have circular imports like this. Quick fix: remove the import from newapp inside comments's models.py and replace with a name reference, like this:
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
post = models.ForeignKey('newapp.NewApp') # <= HERE
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()