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
Related
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.
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())
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)),
]
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
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.