I deleted db and all migrations for resetting my database. But after the deletion when I tried to run
Makemigrations it is showing the error that
OperationalError: no such table : student_app_grade
I have an app named student_app
And in that there is a model with name Grade
this is the full error
python3 manage.py makemigrations
Traceback (most recent call last):
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: student_app_grade
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/ajit/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/ajit/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/ajit/.local/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/ajit/.local/lib/python3.5/site-packages/django/core/management/base.py", line 342, in execute
self.check()
File "/home/ajit/.local/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "/home/ajit/.local/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "/home/ajit/.local/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/ajit/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "/home/ajit/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "/home/ajit/.local/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/ajit/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/ajit/.local/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/ajit/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, 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/ajit/Documents/Choice_feedback/Choice_feedback_main/Choice_feedback_main/urls.py", line 8, in <module>
url(r'^user/', include('registration_app.urls')),
File "/home/ajit/.local/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
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/ajit/Documents/Choice_feedback/Choice_feedback_main/registration_app/urls.py", line 10, in <module>
from registration_app.views import (
File "/home/ajit/Documents/Choice_feedback/Choice_feedback_main/registration_app/views.py", line 11, in <module>
from registration_app.forms import (
File "/home/ajit/Documents/Choice_feedback/Choice_feedback_main/registration_app/forms.py", line 45, in <module>
class AddtionalInformationForm(forms.Form):
File "/home/ajit/Documents/Choice_feedback/Choice_feedback_main/registration_app/forms.py", line 59, in AddtionalInformationForm
for grade in q:
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__
self._fetch_all()
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql()
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/ajit/.local/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/ajit/.local/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: student_app_grade
xlB
this is my forms.py
import roman
from collections import OrderedDict
from django.contrib.auth.forms import (
UserCreationForm,
UserChangeForm,
PasswordChangeForm
)
from django import forms
from django.contrib.auth.models import User
from student_app.models import Grade
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
username = forms.CharField(max_length=24, widget=forms.TextInput(attrs={'name':"username"}))
class Meta:
model = User
fields = (
'username',
'email',
'password1',
'password2'
)
def save(self,commit = True):
user = super(RegistrationForm,self).save(commit = False)
# user.first_name = self.cleaned_data['first_name']
# user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields = (
'email',
'password'
)
class AddtionalInformationForm(forms.Form):
hash_class_ordered = []
hash_div_ordered = []
hash_class = []
hash_div = []
grade_ol = OrderedDict()
grade_ = []
grade_n = []
yq = []
div_ = []
div_n = []
grade_t = ()
q = Grade.objects.all()
for grade in q:
x = grade.grade
temp = x.split("-")
hash_class.append(temp[0])
hash_div.append(temp[1])
for c in hash_class:
if c not in grade_n:
grade_n.append(c)
for d in hash_div:
temp = (d, d)
if temp not in div_:
div_.append(temp)
div_.sort()
for h_c in grade_n:
h_c_n = roman.fromRoman(h_c)
temp = (h_c, h_c_n)
hash_class_ordered.append(temp)
hash_class_ordered.sort()
for c in hash_class_ordered:
c = (c[0], c[0])
yq.append(c)
grade = tuple(yq)
div = tuple(div_)
first_name = forms.CharField(max_length=20)
last_name = forms.CharField(max_length=20)
student_class_grade = forms.ChoiceField(choices=grade)
student_class_div = forms.ChoiceField(choices=div)
roll_no = forms.CharField(max_length=10)
Try,
rebuild migrations: python manage.py makemigrations student_app
migrate: python manage.py migrate
Hope it helps.
I know this post is old but in case anyone else runs into this, the problem could possibly be if you are having a program run before the migrations are being allowed to take place. Such as in the view.py or maybe updating, etc.
Since the db is being reset, the error sounds like something is trying to be done to it even though it was in the middle of being reset (thus not existing).
Check that you don't have typos in student_app/migrations/__init__.py (Do you have two underlines before and after init?? Is there a space somewhere in the filename????)
Does the error appear when running makemigrations?
Delete your migrations and db and paste into your question the full output of makemigrations or the full traceback if the error appears somewhere else (and explain when it appears: you might be importing something too early)
Update: The problem is in line 59 in forms.py (AddtionalInformationForm). In Python constructor code should be in def __init__(self, ...). Please refer to Django's forms docs and learn more about python's object oriented programming. Also: in Django, templates are used to render HTML.
I fixed the same issue as following for my Login app.
(venv) MacBook-Pro:src admin$ python manage.py makemigrations Login
Migrations for 'Login':
Login/migrations/0001_initial.py
- Create model User
(venv) MacBook-Pro:src admin$ python manage.py migrate Login
Operations to perform:
Apply all migrations: Login
Running migrations:
Applying Login.0001_initial... OK
(venv) MacBook-Pro:src admin$ python manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
July 11, 2017 - 13:05:56
Django version 1.11.2, using settings 'CabProj.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C
See the full error traceback. In that, you can find the line in file where you are querying from the db, maybe mostly ( in forms ). You need to temporary delete/comments out the those lines. And then re-run the migrations. You need to keep tracing back and keep deleting/comments outing the lines having query after makemigrations command. At last it will create the migrations files.
Related
I'd like to know where/in which file I should put a set of DRF python code in a Django project. Here's why/what happening to me now.
As I'm trying to migrate from the default sqlite database to postgres, I have a trouble;
$ IS_PRODUCTION=true python manage.py showmigrations
..
django.db.utils.ProgrammingError: relation "django_content_type" does not exist
LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co...
that error tells me relation "django_content_type" does not exist, so I checked the stack trace in the error;
..
File "/root/pg/django/snippetapp/app/urls.py", line 623, in PostViewSet
_content_type_id = ContentType.objects.get_for_model(Post).id
..
It seems that I got the error because I have the set of DRF scripts on ./appname/urls.py,
and I imported/used ContentType, one of core Django classes in the file;
since it seemingly Django loads the top urls.py file in a very early phase, over dealing with ContentType stuff.
So, I guess I got to move the whole set of DRF, so where should I?
But one thing, I guess we have urlpatterns include-ing DRF router urls as such:
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'posts', PostViewSet)
..
urlpatterns = [
path('api/', include(router.urls)),
..
Then isn't we also need to have DRF scripts "before" the ./appname/urls.py -> urlpatterns...?
So I'd also like to know, when moving them to an another file cannot be an option, how can I solve/workaround the issue I have on importing ContentType in the urls.py?
Thanks.
Edit as requested
Here's the the PostViewSet that contains the imported ContentType in it;
from django.contrib.contenttypes.models import ContentType
..
class PostViewSet(viewsets.ModelViewSet):
"""
default Post viewset
"""
_site_id = settings.SITE_ID
# e.g. 3
_content_type_id = ContentType.objects.get_for_model(Post).id
# e.g. 12
comment_count = Comment.objects.filter(content_type_id=_content_type_id).filter(site_id=_site_id).filter(
object_pk=OuterRef('pk')).order_by().annotate(
count=Func(F('id'), function='COUNT')).values("count")
comments = Comment.objects.filter(content_type_id=_content_type_id).filter(site_id=_site_id).filter(
object_pk=OuterRef('pk'))
queryset = Post.objects.all().annotate(
vote_count=Count('voters'),
comment_count=Count('comments'),
# gets the comment count
comment02_count=Subquery(comment_count),
# gets the last comment
comment_last=Subquery(comments.order_by("-submit_date").values("comment")[:1]),
).all()
serializer_class = PostSerializer
permission_classes = [GeneralUserObjectPerm,]
filter_backends = [filters.OrderingFilter, DynamicSearchFilter,]
pagination_class = StandardResultsSetPagination
The entire stack track in the error
# IS_PRODUCTION=true python manage.py showmigrations
/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
""")
Traceback (most recent call last):
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "django_content_type" does not exist
LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/base.py", line 368, in execute
self.check()
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check
databases=databases,
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/urls/resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/urls/resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "/root/.pyenv/versions/3.7.6/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/root/pg/django/snippetapp/app/urls.py", line 615, in <module>
class PostViewSet(viewsets.ModelViewSet):
File "/root/pg/django/snippetapp/app/urls.py", line 623, in PostViewSet
_content_type_id = ContentType.objects.get_for_model(Post).id
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/contrib/contenttypes/models.py", line 51, in get_for_model
ct = self.get(app_label=opts.app_label, model=opts.model_name)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/query.py", line 425, in get
num = len(clone)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/query.py", line 269, in __len__
self._fetch_all()
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/query.py", line 1308, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/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 "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql
cursor.execute(sql, params)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "django_content_type" does not exist
LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co...
#
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 am having a working sqlite database in my local environment. On heroku I am using psql. But I am getting following error when I try to run
$ heroku run python manage.py migrate
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "auth_permission" does not exist
LINE 1: ...ntent_type_id", "auth_permission"."codename" FROM "auth_perm...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 350, in execute
self.check()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check
include_deployment_checks=include_deployment_checks,
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 526, in urlconf_module
return import_module(self.urlconf_name)
File "/app/.heroku/python/lib/python3.6/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 "/app/codeTrial/urls.py", line 20, in <module>
path('', include('coderunner.urls')),
File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/app/.heroku/python/lib/python3.6/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 "/app/coderunner/urls.py", line 4, in <module>
from . import views
File "/app/coderunner/views.py", line 34, in <module>
'perm_obj': Permission.objects.get(name='Can add Questions'),
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 393, in get
num = len(clone)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __len__
self._fetch_all()
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1065, in execute_sql
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_permission" does not exist
LINE 1: ...ntent_type_id", "auth_permission"."codename" FROM "auth_perm...
^
This is not a problem in using psql on heroku I guess, because when I try to copy the same application to another Linux machine and try to recreate sqlite database it gives sqlite3.OperationalError: no such table: auth_permission.
Same error occurs when I try migration after deleting all the 14 migration files from the app/migration folder.
I don't get why at least Django database tables are not getting created. Is it due to anything wrong in the app/models.py file?
In case you need to review my models.py file, here it is:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.validators import MinValueValidator
# Create your models here.
class Questions(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
published_on = models.DateTimeField(auto_now_add=True)
question_text = models.CharField(max_length=200)
question_desc = models.CharField(max_length=500)
pre_code_snippet = models.TextField()
output_format = models.CharField(max_length=500)
timeout = models.IntegerField(default=5, validators=[MinValueValidator(0)])
run_testcase1_input = models.TextField(max_length=50)
run_testcase1_output = models.TextField()
submit_testcase1_input = models.TextField(max_length=50)
submit_testcase1_output = models.TextField()
submit_testcase2_input = models.TextField(max_length=50)
submit_testcase2_output = models.TextField()
times_submitted = models.IntegerField(default=0)
times_correct = models.IntegerField(default=0)
times_wrong = models.IntegerField(default=0)
score = models.IntegerField(default=10,
validators=[MinValueValidator(5)])
class Meta:
verbose_name = 'Questions'
verbose_name_plural = 'Questions'
def __str__(self):
return self.question_text
class Submissions(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE)
submitted_on = models.DateTimeField(auto_now_add=True)
submitted_snippet = models.TextField()
question = models.ForeignKey(Questions, on_delete=models.CASCADE)
class Meta:
verbose_name = 'Submissions'
verbose_name_plural = 'Submissions'
def __str__(self):
return (str(self.username) + '# [' + str(self.question) + ']')
class UserProfile(models.Model):
username = models.OneToOneField(User, on_delete=models.CASCADE)
score = models.IntegerField(default=0,
validators=[MinValueValidator(0)])
class Meta:
verbose_name = "UserProfile"
verbose_name_plural = "UserProfiles"
def __str__(self):
return str(self.username)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(username=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
project/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'coderunner.apps.CoderunnerConfig',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)
I am using Django_2.1.2. I did not find any proper solution for this issue yet. Let me know if I need to provide any other information.
In case you need the full source code, here is my Github link.
Oh yeah, I found the problem. Even after posting my question down here, I was searching for the exact issue, I found a related article where some one has commented there is an issue with his form.py file as per the traceback log. So I thought in my case also there might be some issues in other files beyond my suspected files like models.py, settings.py or migration files. So I checked the Tracebacks again and found this...
File "/app/codeTrial/urls.py", line 20, in <module>
path('', include('coderunner.urls')),
which ultimately executes coderunner/urls.py, where I import coderunner/views.py contents.
File "/app/coderunner/urls.py", line 4, in <module>
from . import views
And in coderunner/views.py I was actually trying to create an object of Permission class outside any view functions/classes. So it is obvious while importing views.py from url.py, views.py gets executed. That means it was accessing the auth model before it was even created, which actually raised the exception auth_permission does not exist. So I handled that code in views.py and tried migrating again... Boom!! Successfully migrated.
In my dev environment there was no issues in migration, because auth model was created by the time I implemented the unhandled code in coderunner/views.py.
You have to comment your root URL routes of all apps
Comment your apps from INSTALLED_APPS list
Run python manage.py migrate. It will migrate the initial migrations of Django itself.
Now uncomment all the comments you've made in the first two steps
I'm trying to deploy my app, but when running migrate.py for the first time, I get an error explaining that a "relation does not exist". Of course it wouldn't, because I haven't been able to migrate yet!
Looking through the traceback, it seems to be getting tripped up in my managers.py file, but I can't understand why my managers would be getting in the way?
pyto(genius) 00:24 ~/genius (master)$ python manage.py migrate
Traceback (most recent call last):
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_comm
and_line
utility.execute()
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 342, in execute
self.check()
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 62, in _run_check
s
issues.extend(super(Command, self)._run_checks(**kwargs))
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
res = instance.__dict__[self.name] = self.func(instance)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "/home/cvcexport/.virtualenvs/genius/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/cvcexport/genius/Genius/urls.py", line 12, in <module>
url(r'^', include('Inventory.urls', namespace="Inventory")),
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "/home/cvcexport/.virtualenvs/genius/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/cvcexport/genius/Inventory/urls.py", line 3, in <module>
from Inventory import views
File "/home/cvcexport/genius/Inventory/views.py", line 67, in <module>
class SummaryView(InventoryView):
File "/home/cvcexport/genius/Inventory/views.py", line 70, in SummaryView
summary_table = build_summary_table()
File "/home/cvcexport/genius/Inventory/views.py", line 62, in build_summary_table
table_query = Purchase.inventory.current_summary_data(**kwargs)
File "/home/cvcexport/genius/Inventory/managers.py", line 31, in current_summary_data
for item in totals:
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__
self._fetch_all()
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 109, in __iter__
for row in compiler.results_iter():
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 789, in results_iter
results = self.execute_sql(MULTI)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
My files are kinda bulky, but this is the Manager that is tripping it up:
class EntryManager(Manager):
def user_create(self, request):
type = request.POST.get('type', None)
label = request.POST.get('label', None)
details = request.POST.get('details', None)
date_added = date.today()
sequence = 1 + self.model.objects.filter(type=type, active=True).count()
label = type + str(sequence) + "- " + label
entry = self.model.objects.create(
type=type,
label=label,
details=details,
date_added=date_added,
sequence=sequence,
user=request.user
)
return entry
def user_update(self, request, pk):
entry = self.model.objects.get(id=pk)
entry.label = entry.type + str(entry.sequence) + "- " + request.POST.get("label")
entry.details = request.POST.get("details")
entry.user = request.user
entry.save()
return entry
def user_delete(self, pk):
entry = self.model.objects.get(id=pk)
successors = self.model.objects.filter(type=entry.type, active=True, sequence__gt=entry.sequence)
for obj in successors:
obj.sequence -= 1
obj.label = obj.label.split(" ", 1)[1]
obj.label = obj.type + str(obj.sequence) + "- " + obj.label
obj.save()
key = entry.id
entry.delete()
return key
def get_entry_set(self, request):
"""
Builds selection lists allowing users to link SWOT entries to strategies. Used in swot-matrix.js with
setStratEntries method.
Args:
Request Delivers two relevant variables:
s_or_w: Indicates "Y-axis" (strength or weakness) requirement.
o_or_t: Indicates "X-axis" (opportunity or threat) requirement.
Returns:
All active entries that match each requested type, packaged in dictionaries and ready for JSON delivery.
"""
# Build Dictionary of active Strengths or Weaknesses
s_or_w = request.GET.get("s_or_w")
strengths_or_weaknesses = self.model.objects.filter(type=s_or_w, active=True)
s_or_w_data = []
for entry in strengths_or_weaknesses:
s_or_w_data.append({
"id": entry.id,
"label": entry.label
})
# Build Dictionary of active Opportunities or Threats
o_or_t = request.GET.get("o_or_t")
opportunities_or_threats = self.model.objects.filter(type=o_or_t, active=True)
o_or_t_data = []
for entry in opportunities_or_threats:
o_or_t_data.append({
"id": entry.id,
"label": entry.label,
})
# Combine for for JSON delivery.
data = {
"s_or_w": s_or_w_data,
"o_or_t": o_or_t_data
}
return data
This is the associated model:
class Entry(GenericObject):
type = models.CharField(max_length=1, choices=choices.ENTRY_CHOICES)
sequence = models.IntegerField()
label = models.CharField(max_length=124)
actions = managers.EntryManager()
objects = models.Manager()
class Meta:
ordering = ["id"]
Am I breaking the rules somewhere? Why is migrate.py complaining about missing columns on a brand new postgres database?
first migrate that particular app. python manage.py migrate app_name. Which will resolve the dependency.
I never figured out what was wrong. The error would trip at different points in my managers here and there, but would always be triggered first in the views. I simply commented out all of the views and urlpatterns, ran the migrations and then reverted the files.
So I was working on my app and added a slugfield to my models. Then as normal went ahead to makemigrations, and a massive red wall of errors appeared.
Traceback (most recent call last):
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: Reader_manga
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm 2016.2.3\helpers\pycharm\django_manage.py", line 41, in <module>
run_module(manage_file, None, '__main__', True)
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 182, in run_module
return _run_module_code(code, init_globals, run_name, mod_spec)
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:/WindowsFolders/Documents/Python/ReaderProject\manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\base.py", line 342, in execute
self.check()
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\urls\resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python35-32\lib\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 "D:/WindowsFolders/Documents/Python/ReaderProject\ReaderProject\urls.py", line 25, in <module>
from Reader import views
File "D:/WindowsFolders/Documents/Python/ReaderProject\Reader\views.py", line 7, in <module>
from .forms import UploadForm
File "D:/WindowsFolders/Documents/Python/ReaderProject\Reader\forms.py", line 12, in <module>
class UploadForm(forms.Form):
File "D:/WindowsFolders/Documents/Python/ReaderProject\Reader\forms.py", line 15, in UploadForm
for manga in mangas:
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\models\query.py", line 256, in __iter__
self._fetch_all()
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\models\query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql()
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\models\sql\compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: Reader_manga
I tried to remove the field I added but no use. I've done pretty much anything that have been suggested on stackoverflow.
I also forgot to add the project to github and now don't have the original database files either.
The model that seem to be giving the error:
class Manga(models.Model):
COMPLETED = 'COMP'
ONGOING = 'ONG'
STATUS_CHOICES = (
(COMPLETED, 'Completed'),
(ONGOING, 'Ongoing'),
)
JAPANESE_MANGA = 'JM'
KOREAN_MANGA = 'KM'
CHINESE_MANGA = 'CM'
UNKNOWN_MANGA = 'UM'
TYPE_CHOICES = (
(JAPANESE_MANGA, 'Japanese Manga'),
(KOREAN_MANGA, 'Korean Manhwa'),
(CHINESE_MANGA, 'Chinese Manhua'),
(UNKNOWN_MANGA, 'Unknown'),
)
authors = models.ManyToManyField(Author)
genres = models.ManyToManyField(Genre)
name = models.CharField(max_length=255, default="")
image = models.ImageField(upload_to=upload_manga_cover)
summary = models.TextField(max_length=1000)
rating = models.IntegerField(default=0)
views = models.IntegerField(default=0)
rank = models.IntegerField(default=0)
alt_names = models.TextField(max_length=400, default="")
type = models.CharField(
max_length=255,
choices=TYPE_CHOICES,
default=UNKNOWN_MANGA
)
status = models.CharField(
max_length=255,
choices=STATUS_CHOICES,
default=ONGOING,
)
released = models.DateField()
date_added = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
Tell me what more you need to know to be able to help and I'll add it.
The fix for me was to run
python manage.py makemigrations app_name
instead of
python manage.py makemigrations
See this related answer: https://stackoverflow.com/a/25843194/2893090
So the fastest way to fix this issue was to just copy everything over into a new project(could probably just remove selected parts and re-add them)
Then just made the app again, copied the settings and models over. Ran makemigrations then migrate. Then I could just simply copy over the views, urls, and everything else.
What went wrong? Maybe something happened to the migrations, and doing the migrations from scratch again helped solve the problem.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
This was the tip given when I was trying to run migrate. I did the above thing and it worked for me.
Solution 1
You can delete 'db.sqlite' if you don't have some critical data and
and run python manage.py migration
It is worked for me. It seems that python manage.py migration doesn't see if you delete table from DB by drop table "your table name". Thanks to Petar Luketina for giving hint above
Solution 2
There is a table django_migration in sqlite3 or in your DB where it keeps the record of migrations. If you manually deleted the table from DB. Then, you should delete it also from DB using
delete from django_migrations where id='"ID of migration that needed to replied"';
Otherwise, migrations will be not applied found in this StackOverflow thread
so simply do migrations
open your Terminal/commandline/git bash based on your operating system and run the following
python manage.py makemigrations
python manage.py migrate