I'm building a fairly simple application, research, in my Django project that uses Django-CMS. (It's my first ground-up attempt at a project/application.) Its main purpose is to store various intellectual assets (i.e article, book, etc. written by a researcher).
The problem is that when I point the browser to /research/ I get an error saying that the table 'research_journal' doesn't exist ("no such table").
I'm using Djnago 1.6.5 with a sqlite3 database.
Looking at python manage.py sql research yields:
BEGIN;
CREATE TABLE "research_researchbase" (
"id" integer NOT NULL PRIMARY KEY,
"pub_date" datetime NOT NULL,
"authors" varchar(200) NOT NULL,
"year" varchar(25) NOT NULL,
"title" varchar(200) NOT NULL,
"subtitle" varchar(200) NOT NULL,
"image_id" integer NOT NULL REFERENCES "filer_image" ("file_ptr_id"),
"link" varchar(200) NOT NULL
)
;
CREATE TABLE "research_journal" (
"researchbase_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "research_researchbase" ("id"),
"journal" varchar(200) NOT NULL,
"abstract" text NOT NULL,
"citation" varchar(200) NOT NULL
)
;
CREATE TABLE "research_encyclopedia_chapter" (
"researchbase_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "research_researchbase" ("id"),
"encyclopedia" varchar(200) NOT NULL,
"publisher" varchar(200) NOT NULL,
"summary" varchar(200) NOT NULL
)
;
CREATE TABLE "research_book" (
"researchbase_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "research_researchbase" ("id"),
"publisher" varchar(200) NOT NULL,
"summary" varchar(200) NOT NULL
)
;
COMMIT;
I've run python manage.py migrate research and get:
/Users/XXX/Documents/repos/sfs/env/lib/python2.7/site-packages/app_data/fields.py:2: DeprecationWarning: django.utils.simplejson is deprecated; use json instead.
from django.utils import simplejson as json
Running migrations for research:
- Nothing to migrate.
- Loading initial data for research.
Installed 0 object(s) from 0 fixture(s)
I've run python manage.py syncdb and get the following:
Syncing...
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Synced:
> djangocms_admin_style
> django.contrib.auth
> django.contrib.contenttypes
> django.contrib.sessions
> django.contrib.admin
> django.contrib.sites
> django.contrib.sitemaps
> django.contrib.staticfiles
> django.contrib.messages
> mptt
> south
> sekizai
> django_select2
> hvad
Not synced (use migrations):
- djangocms_text_ckeditor
- cms
- menus
- djangocms_style
- djangocms_column
- djangocms_file
- djangocms_flash
- djangocms_googlemap
- djangocms_inherit
- djangocms_link
- djangocms_picture
- djangocms_teaser
- djangocms_video
- reversion
- polls
- djangocms_polls
- aldryn_blog
- easy_thumbnails
- filer
- taggit
- research
(use ./manage.py migrate to migrate these)
Here's the models.py:
from django.db import models
from django.utils import timezone
from filer.fields.image import FilerImageField
import datetime
class ResearchBase(models.Model):
pub_date = models.DateTimeField('date published')
authors = models.CharField(max_length=200)
year = models.CharField(max_length=25)
title = models.CharField(max_length=200)
subtitle = models.CharField(max_length=200, blank=True)
image = FilerImageField()
link = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return self.title
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Journal(ResearchBase):
journal = models.CharField(max_length=200)
abstract = models.TextField()
citation = models.CharField(max_length=200)
class Encyclopedia_Chapter(ResearchBase):
encyclopedia = models.CharField(max_length=200)
publisher = models.CharField(max_length=200)
summary = models.CharField(max_length=200)
class Book(ResearchBase):
publisher = models.CharField(max_length=200)
summary = models.CharField(max_length=200)
Here's my views.py (note that I am passing two objects through render, ignore the fact that I have yet to include the class Books in the whole deal):
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from django.template import RequestContext, loader
from research.models import Journal, Encyclopedia_Chapter, Book
def research_index(request):
latest_journal_list = Journal.objects.order_by('-pub_date')[:5]
latest_chapter_list = Encyclopedia_Chapter.objects.order_by('-pub_date')[:5]
context = {
'latest_journal_list': latest_journal_list,
'latest_chapter_list': latest_chapter_list
}
return render(request, 'research/index.html', context)
def journal_detail(request, journal_id):
journal = get_object_or_404(Journal, pk=journal_id)
return render(request, 'research/journal_detail.html', {'journal': journal})
def chapter_detail(request, chapter_id):
chapter = get_object_or_404(Encyclopedia_Chapter, pk=chapter_id)
return render(request, 'research/chapter_detail.html', {'chapter': chapter})
Here's the application's url.py:
from django.conf.urls import patterns, url
from research import views
urlpatterns = patterns('',
url(r'^$', views.research_index, name='research'),
url(r'^(?P<journal_id>\d+)/$', views.journal_detail, name='journal_detail'),
url(r'^(?P<chapter_id>\d+)/$', views.chapter_detail, name='chapter_detail'),
)
Here's the index.html template:
{% extends 'research/base.html' %}
{% block research_content %}
<div class="container">
<div class="row featurette">
<h3 id="research">Peer-reviewed Journal Articles</h3>
{% if latest_journal_list %}
<ul id="research">
{% for journal in latest_journal_list %}
<li id="research">
<img src="{{ journal.image.url }}" id="research">
<h4>{{ journal.journal }}</h4>
<h5>{{ journal.title }}</h5>
Read More
</li>
{% endfor %}
</ul>
{% else %}
<p>No journals are available.</p>
{% endif %}
</div>
<div class="row featurette">
<h3 id="research">Encyclopedia Chapters</h3>
{% if latest_chapter_list %}
<ul id="research">
{% for chapter in latest_chapter_list %}
<li id="research">
<img src="{{ chapter.image.url }}" id="research">
<h4>{{ chapter.journal }}</h4>
<h5>{{ chapter.title }}</h5>
Read More
</li>
{% endfor %}
</ul>
{% else %}
<p>No encyclopedia chapters are available.</p>
{% endif %}
</div>
</div>
{% endblock %}
Just in case it matters, here's my cms_app.py:
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class ResearchApp(CMSApp):
name = _("Research App")
urls = ["research.urls"]
app_name = "research"
apphook_pool.register(ResearchApp)
Use:
python manage.py migrate --run-syncdb
As stated in this comment by Benyamin Jafari:
--run-syncdb - Creates tables for apps without migrations.
Also don't forget to specity app path. For example:
python manage.py makemigrations app
python manage.py migrate app
For django 1.10 you may have to do python manage.py makemigrations appname.
If anyone finds that any of the suggested:
python manage.py makemigrations
python manage.py migrate
python manage.py migrate --run-syncdb
fail, you may need to add a folder named "migrations" inside the app directory, and create an empty __init__.py file.
It looks like there was an issue with my migration.
I ran ./manage.py schemamigration research --auto and found that many of the fields didn't have a default specified.
So, I ran ./manage.py schemamigration research --init followed by ./manage.py migrate research
Rerunning the server from there did the trick!
The issue may be solved by running migrations.
python manage.py makemigrations
python manage.py migrate
perform the operations above whenever you make changes in models.py.
This error comes when you have not made migrations to your newly created table,
So,firsty write command on cmd as: python manage.py makemigrations and then write another command for applying these migrations made by makemigrations command: python manage.py migrate
Running the following commands solved this for me
python manage.py migrate
python manage.py makemigrations
python manage.py makemigrations appName
Run this command below:
"migrate" with "--run-syncdb" creates tables for apps without migrations.
python manage.py migrate --run-syncdb
This is the full description about "migrate" with "--run-syncdb":
--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.
You can check the Django documentation about "migrate" with "--run-syncdb".
I got through the same error when I went on to the admin panel.
You ought to run this instead-: python manage.py migrate --run-syncdb.
Don't forget to include migrate, I ran:
python manage.py make migrations and then
python manage.py migrate
Still when the error persisted I tried it with the above suggested command.
I'm using Django 1.9, SQLite3 and DjangoCMS 3.2 and had the same issue. I solved it by running python manage.py makemigrations. This was followed by a prompt stating that the database contained non-null value types but did not have a default value set. It gave me two options: 1) select a one off value now or 2) exit and change the default setting in models.py. I selected the first option and gave the default value of 1. Repeated this four or five times until the prompt said it was finished. I then ran python manage.py migrate. Now it works just fine. Remember, by running python manage.py makemigrations first, a revised copy of the database is created (mine was 0004) and you can always revert back to a previous database state.
If you get to the bottom of this list and find this answer, I am almost sure it will solve all your issues :)
In my case, I had dropped a database table and I was not getting anywhere with makemigrations and migrate
So I got a very detailed answer on how to reset everything on this link
The Thing that worked for me:
Find out which migrations in your migration folder created the table if not add the class in your models.py.
If the class already exist in your models.py, try to delete that one and run python manage.py makemigrations <appname>
And while migrating fake that migrations as your error might say table not found to delete using python manage.py migrate <yourappname> --fake
Add the class again and makemigrations again python manage.py makemigrations <appname>.
And finally migrate again python manage.py migrate <appname>
Happened to me. It usually happens when we're doing a lot of changes without checking if each individual changes are correctly applied or not (use migrate and makemigrations after each change in tables/cration of tables).
Now what you can try are -
python manage.py migrate (app name)
python manage.py makemigrations
python manage.py makemigrations (app name)
even if above did not worked then what you can do is -
go to migration folder inside your app folder and then delete files that might have caused error(each time you migrate, a new file will be added here to reflect changes, new tables). So find those files and delete those files, which may cause error. And then again apply migrate and makemigrations.
Even if it did not worked, then below code might work.
python manage.py migrate --run-syncdb
Even if above three things did not worked at last, then you should delete db.sqlite3 file which stores your tables and simply create another db.sqlite3 (of course using vs code or pycharm or any coding environment else computer will create text file). Then after creationg another db.splite3,
python manage.py migrate (app name)
python manage.py makemigrations
python manage.py makemigrations (app name)
This happened to me and for me it was because I added db.sqlite3 as untracked from repository. I added it and pushed it to server so it worked properly.
Also run makemigartions and migrate after doing this.
In my case, it was solved by resetting the DB (dev environment actually), by running the reset_db command from Django-Extensions :
python manage.py reset_db
After that I ran the following commands :
python manage.py makemigrations
python manage.py migrate
I'm using Django CMS 3.4 with Django 1.8.
I stepped through the root cause in the Django CMS code.
Root cause is the Django CMS is not changing directory to the directory with file containing the SQLite3 database before making database calls. The error message is spurious. The underlying problem is that a SQLite database call is made in the wrong directory.
The workaround is to ensure all your Django applications change directory back to the Django Project root directory when changing to working directories.
Close the Terminal and again open it and run the following commands:
python manage.py migrate (app name)
python manage.py makemigrations
python manage.py makemigrations (appname)
Related
I am Building a Webapp and I am stuck on an Error.
What i am trying to do
I am making a GeoDjango app using Gdal , OSGeo , Postgresql , Postgis. All of them are successfuly installed.
Tutorial :- I am following this Tutorial
When i try to open the Shop panel in Django Admin then it is keep showing me
relation "mains_shop" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "mains_shop"
And when i delete it and migrate again
then it shows
ValueError: String input unrecognized as WKT EWKT, and HEXEWKB.
But deleting migrations is solving ValueError .
models.py
class Shop(models.Model):
name = models.CharField(max_length=100)
location = models.PointField()
address = models.CharField(max_length=100)
city = models.CharField(max_length=50)
admin.py
#admin.register(Shop)
class ShopAdmin(OSMGeoAdmin):
list_display = ('name', 'location')
settings.py
INSTALLED_APPS = [
'django.contrib.gis',
]
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': '-------',
'USER': '-------',
'PASSWORD': '-------',
'HOST': 'localhost',
'PORT': '',
}
}
What have i tried
First time when error appears then i think that GDal would not installed then I reinstalled it and it successfully installed.
I have reinstalled PostGis .
I have also seen many answers but nothing worked for me.
I have applied migrations many times.
I also tried python manage.py migrate --fake.
I don't know what am i doing wrong.
Any help would be appreciated.
Thank You in Advance.
I know this is not the best solution but it works for me.
This problem occurred to me after I removed my tables in database manually.
my solution:
first of all I removed all of the migration files related to the model which showed in error log. ( you should remove migrations related to Shop model)
change the name of models. (you can change it to Shop2)
run makemigrations and migrate command
change model names back. (change it to Shop again)
make migrations and migrate again
after these steps the problem fixed for me.
also after these step you can delete all new migration files and make migrations again to have only one migration file.
I was facing the same issue for one of the migration file I was generating for model. After spending couple of hours, I came to resolve it by deleting those migration files from django_migrations table.
python manage.py dbshell
select * from django_migrations;
You will see list of all migrations your app wise, delete all those throwing error.
delete from django_migrations where id>=xx
\q
python manage.py migrate
I am having these ProgrammingErrors occurring on my production server lately. The page which the user is submitting a form at is a UserCreateView and is being redirected to the phone-verification page. The error reads:
Internal Server Error: /phone-verification/
ProgrammingError at /phone-verification/
column quiz_sitting.percent_correct does not exist
LINE 1: ...rrect_questions", "quiz_sitting"."current_score", "quiz_sitt...
^
I am not sure why its looking at quiz_sitting in the database because /phone-verification/ has nothing to do with that. The view for /phone-verification/ looks like this:
#login_required
def phone_verify_check(request):
employee = request.user
phone_verify, _ = PhoneVerify.objects.get_or_create(employee=employee)
login_tracker = EmployeeLogin.objects.create(employee=employee, ip_address=get_client_ip(request))
login_tracker.save()
if phone_verify.verified:
return redirect('dashboard')
else:
return redirect('resend')
I am using Django tenant schemas for handling subdomains which means when I run a migration it looks like:
python manage.py makemigrations
python manage.py migrate_schemas --shared
python manage.py migrate_schemas --tenant
I recently deleted all my migrations because I was having these ProgrammingErrors on another page and then I ran the makemigrations etc again and it seemed to have fix it. But now it is occurring again. I really hope there isn't some sort of corruption in the database like columns being mixed up. Any help is greatly appreciated!
When i enter django admin interface and click "Articles" i got Error:
OperationalError at /admin/categories/article/
no such table: categories_article
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/categories/article/
Django Version: 1.9
Exception Type: OperationalError
Exception Value:
no such table: categories_article
Exception Location: \Envs\django19\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 323
Python Executable: \Envs\django19\Scripts\python.exe
Python Version: 3.6.3
admin.py
from django.contrib import admin
from .models import Category, Article
admin.site.register(Category)
admin.site.register(Article)
models.py
from django.db import models
class Category(models.Model):
category_name = models.CharField(max_length=200)
class Article(models.Model):
title = models.CharField(max_length=200)
text = models.TextField(max_length=20000)
What should i do to create new "Article" object in django admin?
The problem is with your migrations but it is difficult to say which file is causing the migration error. You have to check each migration file in migrations directory. It basically occurs because you have a migration in which you have already created the table Articles and somehow django skipped that migration, created the new migration file and marked previous migration as successful. Try one of these ways
1) One way of doing this is find the migration file that creates Article table, delete that migration file and change the dependency of the next migration file to the previous migration file or else django will throw an error. And then:
python manage makemigrations
python manage migrate
2) Change the name of Model Article to something else like Articles and then run migration commands:
python manage makemigrations
python manage migrate
3) If none of the above works. This sure will. Delete all migration and rerun all the migrations.
I was trying to subclass AbstractUser and stuck in an error on running migrate, and makemigrations says No changes detected
django.db.utils.ProgrammingError: relation "auth_group" does not exist
model:
class SubClient(AbstractUser):
client_id = models.ForeignKey(Client)
phone = models.CharField(max_length=15)
added in settings.py:
AUTH_USER_MODEL = 'myadmin.SubClient'
This error means the auth_group table does not exist in your database. Which means you did not run Django's migration files (python files describing database structure and its changes over time).
As you have your own models, you first need to create migration files for them by running python manage.py makemigrations.
Then run python manage.py migrate to run all migrations (Django's + yours), this will create all database tables (including auth_croup).
Read the doc to lean more about migrations.
when using AbstractUser could i use django's user's builtin password-reset workflow such as password-reset, password-reset-done etc.
the reason i am asking is that i extended user model using AbstractUser but these built-in function not working and i do not get any error but it redirects me to search page and there is no documentation on the internet regarding this issue:
from django.contrib.auth import views as auth_views
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset.html'),
name='password-reset'),
path('password-reset/done/',
auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'),
name='password-reset-done'),
path('password-reset-confirm/<uidb65>/<token>/',
auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'),
name='password-reset-confirm'),
path('password-reset-complete/s',
auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'),
name='password-reset-complete')
So I've got either a doozy of an issue, or I'm over looking the obvious.
I am getting a TemplateSyntaxError and it's only occurring in production. I temporary turned on DEBUG and it provided zero useful information. I have an index.html page, that loads my tags, it then calls the inclusion tag.
My setup is Django 1.6.5 and using the default Mezzanine setup. (Fabric, Nginx, Gunicorn). Development environment is OpenSuse 12.2 and the deployment environment is some version of Ubuntu (hosted on AWS EC2).
This issue only occurs on the production side and NOT in the development environment. Originally I made the tag a regular tag, and it wasn't even being called at all. The server would silently fail, and act as though it had never attempted to call the tag. (I used logging to prove that it never went into the tag). Now that it is an inclusion_tag (which is what it should be), I get this exception.
Here is the file system paths where the relevant pieces are.
project
bactt_core
templates
base.html
index.html
blog
includes
blog_post_list_include.html
templatetags
__init__.py
bactt_blog_tags.py
The error exactly is
TemplateSyntaxError at /
Invalid block tag: 'get_blogs_by_category', expected 'endblock'
Here is the portion of my index.html template where I am making the call to the inclusion tag. It is dying on the get_blogs_by_category, which is an inclusion_tag. Inside bactt_blog_tags.
<div id="news" class="row">
<div class="panel">
<div class="panel-body">
<h2>News</h2>
{% load bactt_blog_tags %}
{% get_blogs_by_category "News" %}
</div>
</div>
</div>
Here is bactt_blog_tags
from django import template
from django.core.exceptions import ObjectDoesNotExist
#from mezzanine import template
from mezzanine.blog.models import BlogPost, BlogCategory
register = template.Library()
MAX_BLOG_POSTS_TO_RETURN = 5
#register.inclusion_tag('blog/includes/blog_post_list_include.html')
def get_blogs_by_category(categoryTitle):
category = None
postList = []
try:
category = BlogCategory.objects.get(title__exact=categoryTitle)
except ObjectDoesNotExist:
return {'blog_posts':[]}
if category:
for post in BlogPost.objects.all():
categories = post.categories.all()
if category in post.categories.all():
postList.append(post)
if len(postList) > MAX_BLOG_POSTS_TO_RETURN:
postList = postList[0:MAX_BLOG_POSTS_TO_RETURN]
return {'blog_posts': postList}
Thanks for any help you can provide I've already spun my wheels for a least a few hours now.
Edit:
So I renamed the file bactt_blog_tags.py to bb_tags.py and everything now works. I have no idea what the reason for this naming issue is but if somebody could explain that, I would definitely call this answered. Why whatever pathing occurs in development vs. production is also odd.
What ended up being the fix was changing the name of the template tag filename.
It seems that for some reason using bactt_blog_tags.py created some sort of issue, or possible collisions, that were only happening in production.
What is odd to me is that I didn't have any applications called bactt_blog that might have conflicted. The application directory was bactt_core.
I changed the name to bbtags.py and everything worked.
Your TemplateTags directory should be called templatetags.
Django is case-sensitive here because it's a Python module name (hence the __init__.py in the template tag dir).
You also have an uppercase letter in your Templates dir, but that doesn't matter as it's evaluated as part of a filesystem path, not as a Python import.