I encountered an issue while migrating a DB using django:
Traceback (most recent call last): File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "myBlog_category" does not
exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM
"myBlog_ca...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "manage.py", line 22, in
main() File "manage.py", line 18, in main
execute_from_command_line(sys.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py",
line 401, in execute_from_command_line
utility.execute() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py",
line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 330, in run_from_argv
self.execute(*args, **cmd_options) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 368, in execute
self.check() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 392, in check
all_issues = checks.run_checks( File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\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\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 13, in check_url_config
return check_resolver(resolver) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 23, in check_resolver
return check_method() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 408, in check
for pattern in self.url_patterns: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 582, in urlconf_module
return import_module(self.urlconf_name) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File
"", line 991, in _find_and_load File
"", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in
exec_module File "", line 219, in
call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\blog\urls.py", line 8, in
path('', include('myBlog.urls')), File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\conf.py",
line 34, in include
urlconf_module = import_module(urlconf_module) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File
"", line 991, in _find_and_load File
"", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in
exec_module File "", line 219, in
_call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\urls.py", line 2,
in
from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView,
CategoryListView, LikeView, AddCommentView File
"C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\views.py", line 4,
in
from .forms import PostForm, EditForm, CommentForm File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\forms.py", line 6,
in
for item in choices: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 287, in iter
self._fetch_all() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 1303, in _fetch_all
self._result_cache = list(self._iterable_class(self)) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 142, in iter
return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1108, in results_iter
results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1156, in execute_sql
cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 98, in execute
return super().execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\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\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 75, in _execute_with_wrappers
return executor(sql, params, many, context) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py",
line 90, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "myBlog_category" does not
exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM
"myBlog_ca...
I deployed the app to heroku and got errors so I tried to change the sqlite db to psql before commiting it to heroku but after doing this tutorial migrations did not work anymore, I got stuck on the 3rd step of the tutorial.
I tried the following:
Delete migrations folder from myBlog
Delete db.sqlite3 file
After removing the files/folders above I tried python manage.py makemigrations and got the following error:
Traceback (most recent call last):
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "myBlog_category" does not exist
LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca...
^
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\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py",
line 401, in execute_from_command_line
utility.execute()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py",
line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 368, in execute
self.check()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 392, in check
all_issues = checks.run_checks(
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\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\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 23, in check_resolver
return check_method()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 408, in check
for pattern in self.url_patterns:
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 582, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in call_with_frames_removed
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\blog\urls.py", line 8, in
path('', include('myBlog.urls')),
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\conf.py",
line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in _call_with_frames_removed
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\urls.py", line 2,
in
from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView,
CategoryListView, LikeView, AddCommentView
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\views.py", line 4,
in
from .forms import PostForm, EditForm, CommentForm
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\forms.py", line 6,
in
for item in choices:
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 287, in iter
self._fetch_all()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 1303, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 142, in iter
return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1108, in results_iter
results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1156, in execute_sql
cursor.execute(sql, params)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 98, in execute
return super().execute(sql, params)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\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\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py",
line 90, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "myBlog_category" does not exist
LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca...
Trying to run the server locally now, doesn't work.
While deploying it to heroku I got ProgrammingError - something close to what I get now. I tried to run:
heroku run python manage.py migrate
But got the app would return me the same error as the same traceback at the begging of the post.
My settings.py file:
"""
Django settings for blog project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
import django_heroku
import dj_database_url
from decouple import config
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-97gr5qi*888x%%n!=yp(uf*xz!8(jucnfd!ln+_zkyg#8#e5th'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myBlog',
'members',
'ckeditor',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware'
]
ROOT_URLCONF = 'blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.postgresql_psycopg2',
'NAME' : 'my_db',
'USER' : 'hero',
'PASSWORD' : 'my_db # 123',
'HOST' : 'localhost',
'PORT' : '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
django_heroku.settings(locals())
For any other additional required informations please let me know.
Edit 1:
My models.py
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self) :
return self.name
def get_absolute_url(self) :
return reverse('home')
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField()
profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile")
website_url = models.CharField(max_length=255, null=True, blank=True)
facebook_url = models.CharField(max_length=255, null=True, blank=True)
instagram_url = models.CharField(max_length=255, null=True, blank=True)
twitter_url = models.CharField(max_length=255, null=True, blank=True)
pinterest_url = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return str(self.user)
def get_absolute_url(self) :
return reverse('home')
class Post(models.Model):
title = models.CharField(max_length=255)
header_image = models.ImageField(null=True, blank=True, upload_to="images/")
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='uncategorized')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
# Create your models here.
def get_absolute_url(self):
return reverse('article-detail', args=(str(self.id),))
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
views.py for myBlog app:
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Category, Comment
from .forms import PostForm, EditForm, CommentForm
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator
# Create your views here.
def LikeView(request, pk):
post = Post.objects.get(id=pk)
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('article-detail', args=[str(pk)]))
class HomeView(ListView):
model = Post
template_name = 'home.html'
ordering = ['-post_date']
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(HomeView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
return context
class ArticleDetailView(DetailView):
model = Post
template_name = 'article_details.html'
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
liked = False
if stuff.likes.filter(id=self.request.user.id).exists():
liked = True
total_likes = stuff.total_likes()
context["cat_menu"] = cat_menu
context["total_likes"] = total_likes
context["liked"] = liked
return context
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
def CategoryListView(request):
cat_menu_list = Category.objects.all()
return render(request, 'category_list.html', {'cat_menu_list': cat_menu_list})
def CategoryView(request, cats):
category_posts = Post.objects.filter(category=cats.title().replace('-', ' '))
return render(request, 'categories.html', {'cats': cats.title().replace('-', ' '), 'category_posts': category_posts})
class AddCategoryView(CreateView):
model = Category
fields = '__all__'
template_name = 'add_category.html'
class UpdatePostView(UpdateView):
model = Post
template_name = 'update_post.html'
form_class = EditForm
class DeletePostView(DeleteView):
model = Post
template_name = 'delete_post.html'
success_url = reverse_lazy('home')
class AddCommentView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'add_comment.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
success_url = reverse_lazy('home')
You shouldn't have deleted the migrations folder. Add this folder to your application and add the init file to it. Then create migrations locally. You have to create migrations locally. Heroku should not (and will not) create migration files. Heroku is just executing your code.
Also, if the data in the database is not important, you can re-create db to update the migration table. Or you can update it manually.
Steps
1. Creating a migration folder
cd ./your_app
mkdir migrations
cd migrations
touch __ini__.py
2. Creating migrations
./manage.py makemigrations
3. Pushing on heroku
4. Applying migrations
heroku run python manage.py migrate
P.S: I think Heroku has the tools to manage the Django app. Please refer to the documentation. I think applying migrations should be automatic.
You should performing steps 1-3 locally.
You can re-create the database on heroku or reset it. If you are re-creating the database, do not forget to change the access parameters in the project settings
Related
Premise: I'm a starter[Plz be kind and patient]
When i try to run commands in the terminal like:
python manage.py makemigrations audioma_manager
or
python manage.py runserver
or
python manage.py migrate
or
python manage.py --run-syncdb
where
audioma_manager is the name of my project
I tried also with the name of my app
I get this excetion code, I searched lots on the net but any kind of solution works with my problem:
Traceback (most recent call last):
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_session
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\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle
self.check(databases=[database])
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 423, in check
databases=databases,
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\39371\AppData\Local\Programs\Python\Python37\lib\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 "C:\Users\39371\audioma_manager\audioma_manager\urls.py", line 20, in <module>
path('transcription_form/', include('transcription_form.urls')),
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\39371\AppData\Local\Programs\Python\Python37\lib\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 "C:\Users\39371\audioma_manager\transcription_form\urls.py", line 2, in <module>
from .views import upload
File "C:\Users\39371\audioma_manager\transcription_form\views.py", line 4, in <module>
from .forms import UploadForm
File "C:\Users\39371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users\39371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 34, in _get_session_from_db
expire_date__gt=timezone.now()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 431, in get
num = len(clone)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 262, in __len__
self._fetch_all()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\39371\AudioManVenv\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\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_session
This is my setting file( I'm using django-environ to keep secret some variables):
import environ
import os
from pathlib import Path
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
DJANGO_SETTINGS_MODULE="audioma_manager.settings"
# Set the project base directory
BASE_DIR = Path(__file__).resolve().parent.parent
# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
# False if not in os.environ because of casting above
DEBUG = env('DEBUG')
# Raises Django's ImproperlyConfigured
# exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
# Parse database connection url strings
# like psql://user:pass#127.0.0.1:8458/db
#For production
#DATABASES = {
# read os.environ['DATABASE_URL'] and raises
# ImproperlyConfigured exception if not found
#
# The db() method is an alias for db_url().
'default': env.db(),
# read os.environ['SQLITE_URL']
#'extra': env.db_url(
#'SQLITE_URL',
#default='sqlite:///tmp/my-tmp-sqlite.db'
# )
#}
CACHES = {
# Read os.environ['CACHE_URL'] and raises
# ImproperlyConfigured exception if not found.
#
# The cache() method is an alias for cache_url().
'default': env.cache(),
#instance of sensibile data from .env file
}
API_URL= {
env('API_URL')
}
API_VERSION={
env('API_VERSION')
}
API_USERNAME={
env('API_USERNAME')
}
API_PASSWORD={
env('API_PASSWORD')
}
API_ENDPOINT_SOURCES={
env('API_ENDPOINT_SOURCES')
}
DEFAULT_DIR_PATH={
env('DEFAULT_DIR_PATH')
}
DEFAULT_NAME_FILE_PATTERN={
env('DEFAULT_NAME_FILE_PATTERN')
}
API_ENDPOINT_LOGIN={
env('API_ENDPOINT_LOGIN')
}
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'transcription_form',
'corsheaders',
'rest_framework'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware'
]
ROOT_URLCONF = 'audioma_manager.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'audioma_manager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
#Local db for tests
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'USER': 'USER',
'PASSWORD': 'PASS',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': '\\Users\\39371\\audioma_manager\\audioma_manager\\logs\\debug.log',
},
},
'loggers': {
'transcription_form.client_transcription_api': {
'handlers': ['file'],
'level': 'INFO'
},
},
}
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:8080',
)
My client:
from audioma_manager.settings import API_ENDPOINT_LOGIN, API_PASSWORD, API_URL, API_USERNAME, API_VERSION
from django.contrib.sessions.backends.db import SessionStore
import requests
from requests.structures import CaseInsensitiveDict
#class API management
class GetAPISources:
#authentication to aziendal api
def auth_api(self):
url = API_URL + API_VERSION + API_ENDPOINT_LOGIN
auth_email = API_USERNAME
auth_password = API_PASSWORD
list_of_auth = [auth_email,auth_password]
response= requests.post(url,list_of_auth)
if response.status_code==400:
#manage exception code; return null
return False
token=response['token']
#instance of SessionStore
s=SessionStore()
s['auth_token']=token
# saves the current token
s.save()
#implement a method who calls API endpoint from InfojuiceAPi with representation=1
def call_api(self,endpoint):
api_repr='&representation=1'
s=SessionStore()
session_stored = s.load()
auth_token=session_stored['auth_token']
#used endpoint so i can customize the type of endpoint everytime i call the function
#example--> endpoint='/sources' ; endpoint='/customers'
url = API_URL + API_VERSION + endpoint + api_repr
headers = CaseInsensitiveDict()
headers["Accept"]="application/json"
headers["Authorization"]="token " + auth_token
response= requests.get(url,headers=headers)
if response.status_code==401:
self.auth_api()
self.call_api(endpoint)
return response
My Model:
from django.db import models
# Create your models here.
class Transcription(models.Model):
id = models.BigAutoField
file_name = models.CharField(max_length=10000)
created_at = models.DateTimeField(auto_now_add=True, name='created_at')
updated_at = models.DateTimeField(auto_now=True, name='updated_at')
def __str__(self):
return self.file_name
My Form:
from django import forms
from .client_transcpition_api import GetAPISources
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
class UploadForm(forms.Form):
lang = forms.CharField(label='Lingua', max_length=100, help_text = "Inserisci la lingua del contenuto")
source = forms.CharField(label='Fonte', help_text = "Seleziona la fonte del contenuto" , widget=forms.Select(choices=source_choice))
data = forms.DateField(label='data', help_text = "Seleziona la data del contenuto ", max_length=100)
time = forms.TimeField(label='ora', help_text = "Seleziona l' orario del contenuto", max_length=100)
extension = forms.CharField(label='estensione', help_text = "Seleziona l'estensione del contenuto", max_length=100)
file = forms.FileField(label='file da caricare', help_text = "Seleziona il file da mandare in trascrizione")
My views:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadForm
def upload(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = UploadForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# redirect to a new URL:
#this url is only temp, evaluate better how to do
return HttpResponseRedirect('/thanks/')
else:
form = upload()
return render(request, 'upload.html', {'form': form})
My template:
<!DOCTYPE html>
{% Block Content %}
<h2>Upload</h2>
<form enctype="multipart/form-data" method="post" action="/foo/">
<!-- we need to use this token bc Django makes security controls and requires this token
to be recognize as trust source of code -->
{% csrf_token %}
{{form}}
<input type="file" name="recupero">
<button type="submit">Invio</button>
</form>
In my project I want to:
1)Create repositories, new Django project and first commit.
2)Install Django Environ to upload configurations via .env files.
The configuration must allow you to configure:
authentication to Aziendal API (URL, version, username, password)
path directory for saving the new file to be transcribed
filename pattern (with placeholder for replacing the various components, such as date, source name, title, language, time)
3)Create the Transcription model to save information about content sent in transcription.
Scheme:
ID
file_name Method (String)
created_at (Datetime)
updated_at (Datetime)
4)
Implement a mini client to Aziendal API for THE GET retrieval of sources filtered by name and with the query parameter for rapresentation retrieval.
Use the authentication configured in the configuration file.
5)
Implement a page with a form to load a new transcript with the following fields:
date (date)
source (select sources taken from API)
language (select taken from the configuration)
title
possible profile (optional)
Plz help a young starter.
If u need some source code of my project, just ask:)
Thx for help
xoxo
The most pressing problem here is that you're doing a database call at import time by trying to load a session via
File "C:\Users\39371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users\39371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
which is a big no-no in Django and leads to a chicken-and-egg problem:
you need to make migrations and run migrations to create database tables
Django needs to be able to import your app to do so
your app tries to do a database query from an as-of-yet-nonexistent table (since it's not been migrated yet).
You'll need to do that source_choice at e.g. __init__ time for the form, not at import time.
For the time being, you can replace the source_choice=... line with just source_choice=[] – you won't have any sources to choose from, but you can get your migrations running.
That aside, that session-related code looks strange, especially since you're trying to do so outside of a request context. There will be no valid session to load in that case, since there is no request either. I think you may be confusing Django sessions with whatever the API you're using requires.
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
In my settings.py ive added the following
print(BASE_DIR)
print(MEDIA_URL)
print(MEDIA_ROOT)
It prints the following
d:/OneDrive/!code_projects/!django_projects/mgTut
/media/
d:/OneDrive/!code_projects/!django_projects/mgTut/media/
But when I start the server, I am seeing this error
FileNotFoundError: [Errno 2] No such file or directory: 'd:\\OneDrive\\!code_projects\\!django_projects\\mgTut\\media\\media\\images\\profile_image\\0C0A8604_1_mKlAyCG.JPG'
I'm not quite sure where to go from here. My media_root is supposed to replace, but it doesn't seem to be when it's called.
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR + '/media/').replace('\\', '/')
My models.py class:
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=200, default='')
city = models.CharField(max_length=50, default='')
state = models.CharField(max_length=2, default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
avatar = models.ImageField(upload_to=b'media/images/profile_image',
default='media/images/profile_image/Profile_Blank.PNG')
avatar_thumbnail = ImageSpecField(source='avatar',
processors=[ResizeToFill(100, 100)],
format='JPEG',
options={'quality': 60})
def __str__(self):
return '%s - %s' % (self.user, self.description)
profile = UserProfile.objects.all()[0]
print(profile.avatar_thumbnail.url) # > /media/CACHE/images/982d5af84cddddfd0fbf70892b4431e4.jpg
print(profile.avatar_thumbnail.width) # > 100
Full error:
d:/OneDrive/!code_projects/!django_projects/mgTut
/media/
d:/OneDrive/!code_projects/!django_projects/mgTut/media/
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000002EDDFA09048>
Traceback (most recent call last):
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\apps\registry.py", line 108, in populate
app_config.import_models()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Program Files\Python36\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 "d:\OneDrive\!code_projects\!django_projects\mgTut\account\models.py", line 27, in <module>
print(profile.avatar_thumbnail.url) # > /media/CACHE/images/982d5af84cddddfd0fbf70892b4431e4.jpg
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\__init__.py", line 84, in url
return self._storage_attr('url')
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\__init__.py", line 74, in _storage_attr
existence_required.send(sender=self, file=self)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\dispatch\dispatcher.py", line 193, in send
for receiver in self._live_receivers(sender)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\dispatch\dispatcher.py", line 193, in <listcomp>
for receiver in self._live_receivers(sender)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\registry.py", line 53, in existence_required_receiver
self._receive(file, 'on_existence_required')
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\registry.py", line 61, in _receive
call_strategy_method(file, callback)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\utils.py", line 166, in call_strategy_method
fn(file)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\strategies.py", line 15, in on_existence_required
file.generate()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\__init__.py", line 93, in generate
self.cachefile_backend.generate(self, force)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\backends.py", line 109, in generate
self.generate_now(file, force=force)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\backends.py", line 96, in generate_now
file._generate()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\__init__.py", line 97, in _generate
content = generate(self.generator)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\utils.py", line 152, in generate
content = generator.generate()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\specs\__init__.py", line 150, in generate
img = open_image(self.source)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\pilkit\utils.py", line 21, in open_image
target.seek(0)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\core\files\utils.py", line 20, in <lambda>
seek = property(lambda self: self.file.seek)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\db\models\fields\files.py", line 51, in _get_file
self._file = self.storage.open(self.name, 'rb')
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\core\files\storage.py", line 38, in open
return self._open(name, mode)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\core\files\storage.py", line 300, in _open
return File(open(self.path(name), mode))
FileNotFoundError: [Errno 2] No such file or directory: 'd:\\OneDrive\\!code_projects\\!django_projects\\mgTut\\media\\media\\images\\profile_image\\0C0A8604_1_mKlAyCG.JPG'
UPDATE: It's isolated to the URLs provided by ImageKit. Printing profile.avatar_thumbnail.url is what's throwing the error.
Tried adding replace to it, same problem.
print(profile.avatar_thumbnail.url.replace('\\', '/')) # > /media/CACHE/images/982d5af84cddddfd0fbf70892b4431e4.jpg
print(profile.avatar_thumbnail.width.replace('\\', '/')) # > 100
URLCONF:
from django.conf.urls import url, include
from django.contrib import admin
from django.urls import reverse_lazy
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.views import (
LoginView,
LogoutView,
PasswordResetView,
PasswordResetDoneView,
PasswordChangeView,
PasswordChangeDoneView,
PasswordResetView,
PasswordResetConfirmView,
PasswordResetCompleteView
)
from . import views
urlpatterns = [
url(r'^login/$',
LoginView.as_view(template_name='account/login.html'),
name='login'),
url(r'^logout/$',
LogoutView.as_view(next_page=reverse_lazy('login')),
name='logout'),
url(r'^register/$',
views.register,
name='register'),
url(r'^password_change/$',
PasswordChangeView.as_view(
template_name='account/password_change_form.html'
),
name='password_change'),
url(r'^password_change/done/$',
PasswordChangeDoneView.as_view(
template_name='account/password_change_done.html'
),
name='password_change_done'),
url(r'^password_reset/$',
PasswordResetView.as_view(
template_name='account/password_reset_form.html'
),
name='password_reset'),
url(r'^password_reset/done/$',
PasswordResetDoneView.as_view(
template_name='account/password_reset_done.html'
),
name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
PasswordResetConfirmView.as_view(
template_name='account/password_reset_confirm.html'
),
name='password_reset_confirm'),
url(r'^reset/done/$',
PasswordResetCompleteView.as_view(
template_name='account/password_reset_complete.html'
),
name='password_reset_complete'),
url(r'^admin/',
admin.site.urls),
url(r'^$',
views.home,
name='homepage'),
url(r'^account/',
include('account.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I am new in django.
I have two app named comments and newapp.I am trying to import one of Class (Comment Class) from comments app to newapp. But I get an error called
ImportError: cannot import name 'Comment'
Here is my 'model.py' from comments app
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
# Create your models here.
from newapp.models import NewApp
from newapp.models import Test
class CommentManager(models.Manager):
def filter_by_instance(self, instance):
content_type = ContentType.objects.get_for_model(instance.__class__)
obj_id = instance.id
qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id)
return qs
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
#post = models.ForeignKey(NewApp)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()
def __unicode__(self):
return str(self.user.username)
def __str__(self):
return str(self.user.username)
Here is the 'model.py' code for newapp app
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.text import slugify
#here is the problem code to import below class
from comments.models import Comment
# Create your models here.
class NewApp(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
image = models.FileField(null=True, blank=True)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def _unicode_(self):
return self.title
def _str_(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug":self.slug})
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
# #property
# def comments(self):
# instance = self
# qs = Comment.objects.filter_by_instance(instance)
# return qs
class Test(models.Model):
def _unicode_(self):
return self.title
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = NewApp.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=NewApp)
INSTALLED APP from setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts',
'comments',
'newapp',
]
And finnaly i got error like this
Unhandled exception in thread started by <function check_errors.<locals>.wrapper
at 0x039B27C8>
Traceback (most recent call last):
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\importlib\__i
nit__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\eXp\Desktop\venv\mysite\comments\models.py", line 8, in <module
>
from newapp.models import NewApp
File "C:\Users\eXp\Desktop\venv\mysite\newapp\models.py", line 13, in <module>
import django.comments
ImportError: No module named 'django.comments'
Unhandled exception in thread started by <function check_errors.<locals>.wrapper
at 0x034627C8>
Traceback (most recent call last):
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\importlib\__i
nit__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\eXp\Desktop\venv\mysite\comments\models.py", line 8, in <module
>
from newapp.models import NewApp
File "C:\Users\eXp\Desktop\venv\mysite\newapp\models.py", line 14, in <module>
from comments.models import Comment
ImportError: cannot import name 'Comment'
You're importing newapp from comments and comments from newapp. In python, you can't have circular imports like this. Quick fix: remove the import from newapp inside comments's models.py and replace with a name reference, like this:
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
post = models.ForeignKey('newapp.NewApp') # <= HERE
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()
I am new to djnago.When I am about to run the command
python manage.py migrate
above mentioned error is coming.I don't know where I am wrong.
My populate_rango.py file is
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
import django
django.setup()
from rango.models import Category, Page
def populate():
python_cat = add_cat('Python')
add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")
add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/thinkpython/")
add_page(cat=python_cat,
title="Learn Python in 10 Minutes",
url="http://www.korokithakis.net/tutorials/python/")
django_cat = add_cat("Django")
add_page(cat=django_cat,
title="Official Django Tutorial",
url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")
add_page(cat=django_cat,
title="Django Rocks",
url="http://www.djangorocks.com/")
add_page(cat=django_cat,
title="How to Tango with Django",
url="http://www.tangowithdjango.com/")
frame_cat = add_cat("Other Frameworks")
add_page(cat=frame_cat,
title="Bottle",
url="http://bottlepy.org/docs/dev/")
add_page(cat=frame_cat,
title="Flask",
url="http://flask.pocoo.org")
# Print out what we have added to the user.
for c in Category.objects.all():
for p in Page.objects.filter(category=c):
print "- {0} - {1}".format(str(c), str(p))
def add_page(cat, title, url, views):
p = Page.objects.get_or_create(category=cat, title=title)[0]
p.url=url
p.views=views
p.save()
return p
def add_cat(name,views,likes):
c = Category.objects.get_or_create(name=name)[0]
c.views=views
c.likes=likes
c.save()
return c
# Start execution here!
if __name__ == '__main__':
print "Starting Rango population script..."
populate()
the error is
Applying rango.0002_auto_20151102_1020...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management /__init__.py", line 351, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 343, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 394, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 445, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 222, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 148, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 179, in add_field
self._remake_table(model, create_fields=[field])
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 77, in _remake_table
self.effective_default(field)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 211, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
prepared=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 702, in get_db_prep_value
value = self.get_prep_value(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1868, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: ''
0002_auto_20151102_1020 file is
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rango', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='category',
name='likes',
field=models.IntegerField(default=1),
preserve_default=False,
),
migrations.AddField(
model_name='category',
name='views',
field=models.IntegerField(default=''),
preserve_default=False,
),
]
models.py is
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views=models.IntegerField()
likes=models.IntegerField()
def __unicode__(self): #For Python 2, use __str__ on Python 3
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField()
def __unicode__(self): #For Python 2, use __str__ on Python 3
return self.title
Please help me.Thanks for spending you time...
you have
migrations.AddField(
model_name='category',
name='views',
field=models.IntegerField(default=''), # <---- problem line
preserve_default=False,
),
IntegerField needs integer, not strings ;)
in your Category model, you need
views = models.IntegerField(default=0)
and then run the commands again:
makemigrations
migrate