no such table -- django - database

I am using south, and I have syncdb but alas i get stuck with this database error, can you help me fix this and maybe tell me how to fix something like this in the future.
this missing database table error is comming up in a couple of different places dealing with something called salesflow_contact I have a folder salesflow with a models.py file with a class of Contact with a capitol,
the error shown is from trying to post some content to the table, but i also get an error with the pagination view browsecontacts
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/addacontact
Django Version: 1.4.2
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'south',
'sekizai')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/brian/projects/steprider/steprider/views.py" in Add_a_contact
36. new_contact = form.save(request.user)
File "/home/brian/projects/steprider/salesflow/forms.py" in save
23. contact.save()
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/base.py" in save_base
551. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in insert_query
1593. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
909. for sql, params in self.as_sql():
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in as_sql
872. for obj in self.query.objs
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/django_extensions-0.9-py2.7.egg/django_extensions/db/fields/__init__.py" in pre_save
135. value = unicode(self.create_slug(model_instance, add))
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/django_extensions-0.9-py2.7.egg/django_extensions/db/fields/__init__.py" in create_slug
122. while not slug or queryset.filter(**kwargs):
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in __nonzero__
130. iter(self).next()
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in _result_iter
118. self._fill_cache()
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in _fill_cache
892. self._result_cache.append(self._iter.next())
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in iterator
291. for row in compiler.results_iter():
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in results_iter
763. for rows in self.execute_sql(MULTI):
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
818. cursor.execute(sql, params)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/backends/util.py" in execute
40. return self.cursor.execute(sql, params)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
344. return Database.Cursor.execute(self, query, params)
Exception Type: DatabaseError at /addacontact
Exception Value: no such table: salesflow_contact
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# steprider.salesflow.forms.py
#
# Copyright 2012 BRIAN SCOTT CARPENTER <KlanestroTalisman#gmail.com>
from django.forms import ModelForm
from salesflow import models
from django import forms
from django.template.defaultfilters import slugify
class ContactForm(ModelForm):
description = forms.CharField(widget=forms.Textarea)
class Meta:
model = models.Contact
exclude = ("user","slug")
def save(self, user):
contact = super(ContactForm, self).save(commit=False)
contact.user = user
contact.save()
return contact
class Contact_History_Form:
class Meta:
model = models.Contact_History
exclude = ("user","slug")
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# views.py
#
# Copyright 2012 BRIAN SCOTT CARPENTER <KlanestroTalisman#gmail.com>
from django.shortcuts import render_to_response,get_object_or_404
from django.template import RequestContext
from salesflow.forms import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from salesflow.models import Contact
def home (request):
""" This is the Home view"""
return render_to_response(('index.html') ,context_instance=RequestContext(request))
def server_error(request, template_name='templates/500.html'):
"""
500 error handler.
Templates: `500.html`
Context:
STATIC_URL
Path of static media (e.g. "media.example.org")
"""
t = loader.get_template(template_name)
return HttpResponseServerError(
t.render(Context({'STATIC_URL': settings.STATIC_URL})))
def Add_a_contact(request):
"""give them a page so they can donate and save it to a database."""
if request.method == 'POST':
form = ContactForm(request.POST,request.FILES)
if form.is_valid():
new_contact = form.save(request.user)
return HttpResponseRedirect(reverse(item, args=(new_contact.slug,)))
else:
form = ContactForm()
return render_to_response('salesflow/addacontact.html',{'form': form},context_instance=RequestContext(request))
def browse_contacts(request):
contact_list = Contact.objects.all()
paginator = Paginator(contact_list,15)
page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
contacts = paginator.page(paginator.num_pages)
return render_to_response('salesflow/browsecontacts.html',
{"contacts":contacts,
"site":settings.SITE_DOMAIN},
context_instance=RequestContext(request))

The error is pretty straight forward; you have no table called salesflow_contact.
You'd need to run migrate assuming it has the initial schemamigration salesflow --initial first table creation migration.
syncdb will not create tables for south-managed models, which is most likely your problem. You can bypass this with syncdb --all but if it's truly south-managed, you should run migrate salesflow and it should create the tables assuming you have the schemamigration salesflow --initial migration in there.

Related

Use streamfield in multiple apps: migration error

My wagtail website project is split in different apps, like core, event, publications etc. and I set up my streamfield in core.models.
Now I would like to reuse this streamfield not only in core.models, but also in event.models.
But what's the most elegant (dry) way of defining my streamfield (subclassing StreamBlock) only once and reuse it in all my apps?
My StreamBlock is inspired by the one from the wagtaildemo project:
# core/models.py
class StoryBlock(StreamBlock):
h2 = CharBlock(icon="title", classname="title")
h3 = CharBlock(icon="title", classname="title")
h4 = CharBlock(icon="title", classname="title")
intro = RichTextBlock(icon="pilcrow")
paragraph = RichTextBlock(icon="pilcrow")
aligned_image = ImageBlock(label="Aligned image")
pullquote = PullQuoteBlock()
read_on = ReadOnBlock()
-
# event/models.py
from wagtail.wagtailcore.fields import StreamField
from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel
from core.models import StoryBlock
class EventIndexPage(Page):
body = StreamField(StoryBlock())
content_panels = Page.content_panels + [
StreamFieldPanel('body'),
]
But trying to makemigrations the updated EventIndexPage page model yields a warning that I am trying to add a non-nullable field 'body' to eventindexpage without a default - but this only happens with (stream-)fields on non-core-models.
Passing the requested default value - be it "asdf" or "[]" - to makemigrations build the migration file, but the following migrate fails:
$ python manage.py migrate
...
File "/myproject/venv/lib/python3.5/site-packages/wagtail/wagtailcore/fields.py", line 90, in get_prep_value
return json.dumps(self.stream_block.get_prep_value(value), cls=DjangoJSONEncoder)
File "/myproject/venv/lib/python3.5/site-packages/wagtail/wagtailcore/blocks/stream_block.py", line 205, in get_prep_value
for child in value # child is a BoundBlock instance
File "/myproject/venv/lib/python3.5/site-packages/wagtail/wagtailcore/blocks/stream_block.py", line 205, in <listcomp>
for child in value # child is a BoundBlock instance
AttributeError: 'str' object has no attribute 'block'
Full traceback
If this is connected with my issue: this project will be deployed to openshift, so I'm limited to Django 1.8 when using Python 3. And glad to use wagtail 1.5.
As gasman pointeted out in in his comment, using "" as default value for the migration did the trick.

Python webapp Google app engine: no module named six

The following code should take 2 dates from input.html and display months and years in output.html, but the Google app engine returns an error saying module six is missing, even though I have added all the site packages in my project library.
What am I doing wrong?
import webapp2
import jinja2
import os
import time
import datetime
import sys
from dateutil.rrule import rrule, MONTHLY
sys.path.append(os.path.join(os.path.dirname(__file__), "libs"))
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
class MainHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
return render_str(template, **params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
def get(self):
self.render('input.html')
def post(self):
frmstring=self.request.get('from')
tostring=self.request.get('to')
frm=time.strptime(frms,"%Y-%m")
to=time.strptime(tos,"%Y-%m")
dates = [dt for dt in rrule(MONTHLY, dtstart=frm, until=to)]
months_choices = []
for i in range(1,13):
months_choices.append(datetime.date(2008, i, 1).strftime('%B'))
self.render('output.html',dates = dates,months_choices=months_choices)
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
You need to vendor six into your environment.
Run
pip install -t lib six
Then add these lines to your apppengine_config.py file (or create it)
# appengine_config.py
from google.appengine.ext import vendor
# Add any libraries install in the "lib" folder.
vendor.add('lib')
See https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27#installing_a_third-party_library for more details
The six module is not provided by the AppEngine environment. Have you included it in your lib/ directory?

Unable to use app engine datastore

I have used the getting started guide of app engine.But I am unable to use the datastore.
While running the simple code provided in the guide, i am getting "cannot access apps data" error.
my code :
import cgi
import datetime
import urllib
import webapp2
from google.appengine.ext import db
from google.appengine.api import users
MAIN_PAGE_FOOTER_TEMPLATE = """\
<form action="/sign?%s" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
<hr>
<form>Guestbook name: <input value="%s" name="guestbook_name">
<input type="submit" value="switch"></form>
</body>
</html>
"""
class Greeting(db.Model):
"""Models an individual Guestbook entry with author, content, and date."""
author = db.StringProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
def guestbook_key(guestbook_name=None):
"""Constructs a Datastore key for a Guestbook entity with guestbook_name."""
return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write('<html><body>')
guestbook_name = self.request.get('guestbook_name')
# Ancestor Queries, as shown here, are strongly consistent with the High
# Replication Datastore. Queries that span entity groups are eventually
# consistent. If we omitted the ancestor from this query there would be
# a slight chance that Greeting that had just been written would not
# show up in a query.
greetings = db.GqlQuery("SELECT * "
"FROM Greeting "
"WHERE ANCESTOR IS :1 "
"ORDER BY date DESC LIMIT 10",
guestbook_key(guestbook_name))
for greeting in greetings:
if greeting.author:
self.response.write(
'<b>%s</b> wrote:' % greeting.author)
else:
self.response.write('An anonymous person wrote:')
self.response.write('<blockquote>%s</blockquote>' %
cgi.escape(greeting.content))
# Write the submission form and the footer of the page
sign_query_params = urllib.urlencode({'guestbook_name': guestbook_name})
self.response.write(MAIN_PAGE_FOOTER_TEMPLATE %
(sign_query_params, cgi.escape(guestbook_name)))
class Guestbook(webapp2.RequestHandler):
def post(self):
# We set the same parent key on the 'Greeting' to ensure each greeting
# is in the same entity group. Queries across the single entity group
# will be consistent. However, the write rate to a single entity group
# should be limited to ~1/second.
guestbook_name = self.request.get('guestbook_name')
greeting = Greeting(parent=guestbook_key(guestbook_name))
if users.get_current_user():
greeting.author = users.get_current_user().nickname()
greeting.content = self.request.get('content')
greeting.put()
query_params = {'guestbook_name': guestbook_name}
self.redirect('/?' + urllib.urlencode(query_params))
app = webapp2.WSGIApplication([('/', MainPage),
('/sign', Guestbook)],
debug=True)
I have uploaded the app on the server, but still getting the same error.
Traceback (most recent call last):
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/home/laxman/helloworld/helloworld.py", line 51, in get
for greeting in greetings:
File "/home/laxman/google_appengine/google/appengine/ext/db/__init__.py", line 2326, in next
return self.__model_class.from_entity(self.__iterator.next())
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_query.py", line 2892, in next
next_batch = self.__batcher.next()
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_query.py", line 2754, in next
return self.next_batch(self.AT_LEAST_ONE)
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_query.py", line 2791, in next_batch
batch = self.__next_batch.get_result()
File "/home/laxman/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 604, in get_result
return self.__get_result_hook(self)
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_query.py", line 2528, in __query_result_hook
self._batch_shared.conn.check_rpc_success(rpc)
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1224, in check_rpc_success
raise _ToDatastoreError(err)
BadRequestError: app "dev~helloworld" cannot access app "dev~hellolxmn"'s data
For the dev server the answer is in your the last line of your stacktrace.
app "dev~helloworld" cannot access app "dev~hellolxmn"'s data
You probably have an app.yaml which has changed it's appid, over time and you haven't
created a new datastore. You should show us you current app.yaml.
My guess is your error will be a little different in product, so show the trace for the error in production.
I copied and pasted your code and it seems to be working (I had to change formatting)
What is in your app.yaml? (I named my file aaa.py) this is what i used
application: somename
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: aaa.app

How do I fix this TypeError?

I'm new to python and Google App Engine. I'm trying to refactor this code from Nick Johnson blog to use webapp2 and python 2.7. http://blog.notdot.net/2009/10/Blogging-on-App-Engine-part-1-Static-serving
Anyways, when I run the code below I get this error.
TypeError: get() takes exactly 2 arguments (1 given)
I think it may have something to do with the path variable not being defined, but I don't know how to define it.
import webapp2
from google.appengine.ext import webapp
from google.appengine.ext import db
class StaticContent(db.Model):
body = db.BlobProperty()
content_type = db.StringProperty(required=True)
last_modified = db.DateTimeProperty(required=True, auto_now=True)
def get(path):
return StaticContent.get_by_key_name(path)
def set(path, body, content_type, **kwargs):
content = StaticContent(
key_name=path,
body=body,
content_type=content_type,
**kwargs)
content.put()
return content
class MainHandler(webapp2.RequestHandler):
def get(self, path):
content = get(path)
if not content:
self.error(404)
return
app = webapp2.WSGIApplication([('/', MainHandler)],
debug=True)
The error is raised because the get method of the MainHandler class expects a path parameter.
You should add grouping to the regex in your routing definition to pass the path parameter to the get method:
app = webapp2.WSGIApplication([('(/.*)', MainHandler)],
debug=True)

Database error : no such column: connect_connect.reciever_id

I have created following model
class ConnectToFrom(models.Model):
person = models.ForeignKey(User, null=True)
kiosk = models.ForeignKey(Kiosks, null=True)
class Connect(models.Model):
parent_id = models.ForeignKey("self", null = True, blank = True)
sender = models.ForeignKey(ConnectToFrom, related_name='sent_messages' )
reciever = models.ForeignKey(ConnectToFrom, related_name='received_messages')
.
.
.
I am not able to access Connects to add any connect object through admin site !
Can i not reference same model to two fields ?
I am not able to figure out what exactly is causing the error .
Please help
Traceback :
Environment:
Request Method: GET
Request URL: http://www.example.com:8000/admin/connect/connect/
Django Version: 1.3
Python Version: 2.6.6
Installed Applications:
['broadcast',
'shastra',
'fb_api',
'log',
'nties',
'crc',
'connect',
'network',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'kiosks',
'content',
'home',
'dashboard',
'trial',
'meta',
'oembed']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python26\lib\site-packages\django\contrib\admin\options.py" in wrapper
307. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\contrib\admin\sites.py" in inner
197. return view(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in _wrapper
28. return bound_func(*args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in bound_func
24. return func(self, *args2, **kwargs2)
File "C:\Python26\lib\site-packages\django\contrib\admin\options.py" in changelist_view
1159. 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "C:\Python26\lib\site-packages\django\db\models\query.py" in __len__
82. self._result_cache = list(self.iterator())
File "C:\Python26\lib\site-packages\django\db\models\query.py" in iterator
273. for row in compiler.results_iter():
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py" in results_iter
680. for rows in self.execute_sql(MULTI):
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
735. cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\util.py" in execute
34. return self.cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
234. return Database.Cursor.execute(self, query, params)
Exception Type: DatabaseError at /admin/connect/connect/
Exception Value: no such column: connect_connect.reciever_id
Did you add the receiver field to your model after you initially created the connect_connect table? If so you'll have to manually add that field to your database (Django does not automatically sync changes to your models with your database.)
Just launch your interactive db shell, usually dbshell, and add the field. In MySQL it would be something like:
ALTER TABLE connect_connect ADD COLUMN receiver_id integer;
I'd recommend running manage.py sqlall appname to see how Django would create your db tables now, and then make sure the db matches that by making the necessary changes through your db shell.

Resources