not able to use anaconda packages in django app - django

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

Related

Constantly get an error "no such table" whatever I do

I am pretty new to django and database management as well, therefore there is certainly a possibility that I do not understand some crucial things about them.
I've been trying to solve this error by myriads of ways for a few days (It occured as a result of a declaration of a new field in existing model called Habit), I tried:
resetting database with reset_db (django-extensions)
flushing it with native django flush command (now I do understand
that it was a wrong method)
recreating a whole app in another virtual environment with creation
of fresh databases
faking migrations with --fake (out of desperation basically)
manually changing fields in a db with sql browser
deleting sqlite database manually and making migrations
Here are my models:
from django.db import models
from django.utils import timezone
from datetime import timedelta
import datetime
# Create your models here.
class Day(models.Model): # Creating table for this model didn't cause any trouble
date = models.DateField(auto_now_add=True)
def __str__(self):
return str(self.date)
class Habit(models.Model):
name = models.CharField(max_length=200)
targ_init_time = models.TimeField(auto_created=False, auto_now_add=False, default=datetime.time())
targ_term_time = models.TimeField(auto_created=False, auto_now_add=False, default=datetime.time())
true_init_time = models.TimeField(auto_created=False, auto_now_add=False, blank=True, default=datetime.time())
true_term_time = models.TimeField(auto_created=False, auto_now_add=False, blank=True, default=datetime.time())
is_completed = models.BooleanField(default=False)
day = models.ForeignKey(Day, on_delete=models.CASCADE, related_name='habits') # --That New Field I've added--
def find_duration(self):
total_targ_time = timedelta(hours=self.targ_term_time.hour, minutes=self.targ_term_time.minute) - timedelta(hours=self.targ_init_time.hour, minutes=self.targ_init_time.minute)
total_true_time = timedelta(hours=self.true_term_time.hour, minutes=self.true_term_time.minute) - timedelta(hours=self.true_init_time.hour, minutes=self.true_init_time.minute)
return [total_true_time, total_targ_time]
def format_time(self):
time = self.find_duration()
true = float(".".join(str(time[0]).split(":"))[0:4])
targ = float(".".join(str(time[1]).split(":"))[0:4])
if true < 1:
true = str(int(true * 100)) + ' mins'
else:
true = str(true) + ' hours'
if targ < 1:
targ = str(int(targ * 100)) + ' mins'
else:
targ = str(targ) + ' hours'
return [true, targ]
def find_productivity(self):
total_both_time = self.find_duration()
try:
productivity = int(total_both_time[0] / total_both_time[1] * 100)
except ZeroDivisionError:
productivity=0
return productivity
def __str__(self):
return self.name
Views:
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.template import loader
from datetime import timedelta, time
from .models import Habit
from .forms import HabitForm, EditHabitForm
# Create your views here.
def dayViewHabitIndex(request):
all_habits = Habit.objects.all()
form = HabitForm()
template = loader.get_template("Tracker/one_day_habits.html")
productivity_list = [habit.find_productivity() for habit in all_habits]
try:
median_productivity = int(sum(productivity_list) / len(productivity_list))
except ZeroDivisionError:
median_productivity = 0
context = {'habits_list':all_habits, 'median_productivity':median_productivity, 'form':form}
return HttpResponse(template.render(context, request))
def addHabit(request):
new_habit = HabitForm(request.POST)
if new_habit.is_valid():
new_habit.save()
return HttpResponseRedirect(reverse('Tracker:index'))
def editHabitsTime(request, habit_id):
certain_habit = Habit.objects.get(id=habit_id)
template = loader.get_template('Tracker/editHabitsTime.html')
form = EditHabitForm()
context = {'certain_habit':certain_habit, 'form':form}
return HttpResponse(template.render(context, request))
def editSuccess(request, habit_id, template='Tracker/editHabitsTime.html'):
changes = EditHabitForm(request.POST, instance=Habit.objects.get(id=habit_id))
if changes.is_valid():
changes.save()
return HttpResponseRedirect(reverse('Tracker:index'))
else:
return render(request, template, {'form':form, 'warning':'Something Went Wrong'})
App urls:
from django.urls import path
from . import views
app_name = 'Tracker'
urlpatterns = [
path('', views.dayViewHabitIndex, name='index'),
path('createHabit/', views.addHabit, name='addHabit'),
path('<int:habit_id>/edit/', views.editHabitsTime, name='editHabit'),
path('<int:habit_id>/success/>', views.editSuccess, name='saveChanges'),
]
Forms:
from django.forms import ModelForm
from django.utils.translation import gettext_lazy as _
from django.forms.fields import DateField
from django import forms
from . import models
HABIT_NAMES = zip([habit.name for habit in models.Habit.objects.all()], [habit.name for habit in models.Habit.objects.all()])
class HabitForm(ModelForm):
class Meta:
model = models.Habit
#widgets = {'name': forms.Select(choices=HABIT_NAMES)}
fields = '__all__'
labels = {'name': _(''), 'targ_init_time':_(''), 'targ_term_time':_(''), 'true_init_time':_(''), 'true_term_time':_(''), 'is_completed':_('') }
class EditHabitForm(ModelForm):
class Meta:
model = models.Habit
exclude = ('name', 'targ_init_time', 'targ_term_time', )
Full Error Message:
(WebApp-G_WmOMr9) D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp>python manage.py makemigrations
Traceback (most recent call last):
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: Tracker_habit
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\base.py", line 368, in execute
self.check()
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = checks.run_checks(
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\urls\resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\User\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 "D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp\HabitTracker\urls.py", line 21, in <module>
path('', include('Tracker.urls')),
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\User\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 "D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp\Tracker\urls.py", line 3, in <module>
from . import views
File "D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp\Tracker\views.py", line 12, in <module>
from .forms import HabitForm, EditHabitForm
File "D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp\Tracker\forms.py", line 8, in <module>
HABIT_NAMES = zip([habit.name for habit in models.Habit.objects.all()], [habit.name for habit in models.Habit.objects.all()])
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\models\query.py", line 287, in __iter__
self._fetch_all()
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\models\query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql
cursor.execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: Tracker_habit
Thanks for help in advance!
these queries in your forms are executed and cause the error even before your "makemigrations" is doing the actual makemigrations:
HABIT_NAMES = zip([habit.name for habit in models.Habit.objects.all()], [habit.name for habit in models.Habit.objects.all()])
I would comment it out and try again.
Have you tried running the following command?
python manage.py migrate --run-syncdb
According to doc
--run-syncdb¶
Allows creating tables for apps without migrations. While this isn’t
recommended, the migrations framework is sometimes too slow on large
projects with hundreds of models.

Django unable to resolve the import type

Iam a newbie learning django iam struck here can someone help on this.
i followed this tutorial https://www.youtube.com/watch?v=RMTVAIVrdtM
Iam using pycharm IDE, created on the similar lines but still iam getting the error.
from poll import view as poll_views ### Getting error in this line .....----<<<<<<<
urlpatterns = [
path('admin/', admin.site.urls),
path(''.poll_views.home,name='home'),
path('create/'.poll_views.create, name='create'),
path('vote/<poll_id>'.poll_views.vote, name='vote'),
path('results/<poll_id>'.poll_views.results, name='results'),
]
views.py
from django.shortcuts import render
# Create your views here.
def home(request):
context = {}
return render(request, 'poll/home.html',context)
def create(request):
context = {}
return render(request, 'poll/create.html',context)
def vote(request, poll_id):
context = {}
return render(request, 'poll/vote.html',context)
def results(request, poll_id):
context = {}
return render(request, 'poll/results.html',context)
On terminal
(test) C:\Users\Learner\projects\poll_project>python manage.py migrate
Traceback (most recent call last):
File "C:\Users\Learner\projects\poll_project\manage.py", line 21, in <module>
main()
File "C:\Users\Learner\projects\poll_project\manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 366, in execute
self.check()
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = self._run_checks(
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\commands\migrate.py", line 64, in _run_checks
issues.extend(super()._run_checks(**kwargs))
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\Learner\Envs\test\lib\site-packages\django\urls\resolvers.py", line 407, in check
for pattern in self.url_patterns:
File "C:\Users\Learner\Envs\test\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module
return import_module(self.urlconf_name)
File "c:\users\Learner\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1021, in _gcd_import
File "<frozen importlib._bootstrap>", line 998, in _find_and_load
File "<frozen importlib._bootstrap>", line 977, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Learner\projects\poll_project\poll_project\urls.py", line 19, in <module>
from poll import view as poll_views
ImportError: cannot import name 'view' from 'poll' (C:\Users\Learner\projects\poll_project\poll\__init__.py)
Please find the project folder screenshot below.
this is my folder structure
Can someone please help me where iam going wrong ???
The import statement should be like
If want to import specific view
from poll.views import <nameoftheview> as poll_views
Or if you want to import all the views
import poll.views as poll_views
Update: Correct error in your urls.py (also pointed out by #sheraram)
urlpatterns = [
path('admin/', admin.site.urls),
path('create/', poll_views.create, name='create'),
path('vote/<poll_id>', poll_views.vote, name='vote'),
path('results/<poll_id>', poll_views.results, name='results'),
path('', poll_views.home,name='home'),
]
url takes following argument path(route, view, name{optional})
but you are giving path(route.view, name)
replace . after route by ,

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 DefaultRouter error

I wrote a program to learn django rest framework, but the program I wrote is not executed correctly. I have been looking for it for a long time. I can't find the error. I need someone to help me check the problem from another perspective. Thank you.
models.py
from django.db import models
class Subsystem(models.Model):
name = models.CharField(max_length=36)
class Menu(models.Model):
subsystem = models.ForeignKey(Subsystem, on_delete=models.CASCADE)
name = models.CharField(max_length=36)
serializers.py
from rest_framework.serializers import ModelSerializer
from subsystem.models import Subsystem, Menu
class SubsystemSerializer(ModelSerializer):
class Meta:
model = Subsystem
fields = ('name', )
class MenuSerializer(ModelSerializer):
class Meta:
model = Menu
fields = ('name', 'subsystem')
views.py
from rest_framework.viewsets import ModelViewSet
from subsystem.models import Subsystem, Menu
from subsystem.api.serializers import SubsystemSerializer, MenuSerializer
class SubsystemViewSet(ModelViewSet):
queryset = Subsystem.objects.all()
serializer_class = SubsystemSerializer(queryset)
class MenuViewSet(ModelViewSet):
queryset = Menu.objects.all()
serializer_class = MenuSerializer
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from subsystem.api.views import SubsystemViewSet
router = DefaultRouter()
router.registry(r'subsystems', SubsystemViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
I started trying to run python manage.py runserver but it can't run
error:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x06125FA8>
Traceback (most recent call last):
File "D:\env\python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "D:\env\python\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
self.check(display_num_errors=True)
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "D:\env\python\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "D:\env\python\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 "D:\sc\oa\oaapi\oaapi\urls.py", line 18, in <module>
router.registry(r'subsystems', SubsystemViewSet)
TypeError: 'list' object is not callable
I modified views.py
class SubsystemViewSet(ModelViewSet):
queryset = Subsystem.objects.all()
serializer_class = SubsystemSerializer
But the error still exists
detail:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x065F5FA8>
Traceback (most recent call last):
File "D:\env\python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "D:\env\python\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
self.check(display_num_errors=True)
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "D:\env\python\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "D:\env\python\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 "D:\sc\oa\oaapi\oaapi\urls.py", line 18, in <module>
router.registry(r'subsystems', SubsystemViewSet)
TypeError: 'list' object is not callable
ViewSet's serializer_class should be class itself, not it's instance. You should use serializer_class = SubsystemSerializer instead of serializer_class = SubsystemSerializer(queryset).Rewrite SubsystemViewSet to this:
class SubsystemViewSet(ModelViewSet):
queryset = Subsystem.objects.all()
serializer_class = SubsystemSerializer
Also it should be register instead of registry:
router.register(r'subsystems', SubsystemViewSet)
You can find example of routers usage here.

ImportError: No module named 'models' in Python 3

I have a new Python project, with a models.py file that looks like this:
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
class Metric(models.Model):
users = models.ManyToManyField(User, through = 'Vote')
name = models.CharField(max_length = 255)
class Vote(models.Model):
metric = models.ForeignKey(Metric, on_delete = models.CASCADE)
user = models.ForeignKey(User, on_delete = models.CASCADE)
rating = models.IntegerField(validators = [MinValueValidator(0), MaxValueValidator(10)])
email = models.EmailField
def __str__(self):
return str(self.rating)
and an admin.py file like this:
from django.contrib import admin
from models import Metric, Vote
admin.site.register(Metric)
admin.site.register(Vote)
When running this with Python 2.7.5, launching the app works fine. When I try to run it using Python 3.5.1, I get the error ImportError: No module named 'models', with this backtrace:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x103bd2b70>
Traceback (most recent call last):
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/Users/sashacooper/pyenv/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 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/Users/sashacooper/Desktop/pogroms/crockerometer2/crockerometer/admin.py", line 2, in <module>
from models import Metric, Vote
I've tried adding from __future__ import absolute_import to the start of the admin.py file per similarly titled Stack Overflow posts but it didn't change the error. What's causing it?
In Python 3 you must tell it when you are using relative imports:
from .models import ...
try from .models import Metric, Vote in your admin.py
I have always used:
from myapp.models import ...
Rather than a relative import. Just my personal preference. Perhaps relative import makes more sense if it is the admin.py for myapp, but I still like the explicitness of having the app name in the import.