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.
Related
Use the example code from app engine will give an attribute error. The more strange thing is,
When the batch_size is 100, the first fetch will give an error while if it were set to 10, the second fetch will give the error, when the batch_size is 1, the 25th fetch will give the error. Is it due to the problem of remote API?
Python version: 2.7
App engine sdk version: 1.9.6
query = MyModel.all()
entities = query.fetch(100)
while entities:
for entity in entities:
# Do something with entity
query.with_cursor(query.cursor())
entities = query.fetch(100)
error message:
Traceback (most recent call last):
File "migrate.py", line 77, in <module>
entities = query.fetch(batch_size)
File "/home/kamel/Library/google_appengine/google/appengine/ext/db/__init__.py", line 2157, in fetch
return list(self.run(limit=limit, offset=offset, **kwargs))
File "/home/kamel/Library/google_appengine/google/appengine/ext/db/__init__.py", line 2326, in next
return self.__model_class.from_entity(self.__iterator.next())
File "/home/kamel/Library/google_appengine/google/appengine/ext/db/__init__.py", line 1435, in from_entity
entity_values = cls._load_entity_values(entity)
File "/home/kamel/Library/google_appengine/google/appengine/ext/db/__init__.py", line 1413, in _load_entity_values
value = prop.make_value_from_datastore(value)
File "/home/kamel/labola/src/model/properties.py", line 295, in make_value_from_datastore
return pickle.loads(value)
File "/usr/lib/python2.7/pickle.py", line 1382, in loads
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1083, in load_newobj
obj = cls.__new__(cls, *args)
AttributeError: class Reference has no attribute '__new__
I encountered the same issue when trying to unpickle python3 pickles under python2. The problem was linked to new-style classes becoming default in python3. (source)
Solution for me was to replace class AClass: by class AClass(object):
I read the "what is a metaclass in Python" but am still confused over it.
I am new to python and have been thrown into upgrading it from 2.5 to 2.7.
I have the following:
class UsersDB(db.Model):
Email = db.EmailProperty(required=True,verbose_name='Email *')
Enable = db.BooleanProperty(default=True)
and
class UsersQuickAddForm(forms.ModelForm):
def is_user_exist(self, account):
users_query = UsersDB.all().filter('Email =', account).fetch(1)
if len(users_query) > 0:
return True
return False
class Meta:
model = UsersDB
exclude = ['Enable']
but when I try to execute it on the google site, I get:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 239, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 298, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 84, in LoadObject
obj = import(path[0])
File "/base/data/home/apps/s~ldsdgidev/glen27.371429613087607751/LDSGH.py", line 8, in
from core.decorators import permissionRequired
File "/base/data/home/apps/s~ldsdgidev/glen27.371429613087607751/core/decorators.py", line 7, in
from core.initialization import loginIf
File "/base/data/home/apps/s~ldsdgidev/glen27.371429613087607751/core/initialization.py", line 6, in
import photo_images
File "/base/data/home/apps/s~ldsdgidev/glen27.371429613087607751/core/photo_images.py", line 1, in
from core.db_models import ImagesDB
File "/base/data/home/apps/s~ldsdgidev/glen27.371429613087607751/core/db_models.py", line 222, in
class UsersQuickAddForm(forms.ModelForm):#only account, firstname and last name is required
File "/base/data/home/apps/s~ldsdgidev/glen27.371429613087607751/django/forms/models.py", line 205, in new
opts.exclude, opts.widgets, formfield_callback)
File "/base/data/home/apps/s~ldsdgidev/glen27.371429613087607751/django/forms/models.py", line 145, in fields_for_model
opts = model._meta
AttributeError: type object 'UsersDB' has no attribute '_meta'
and I don't understand what I need to add to the UserDB class to get rid of the error.
Any help would be great!
This isn't anything to do with Python versions, or metaclasses.
ModelForms only work with Django models. db.Model is the App Engine model class, not the Django one. You can't use a modelform with that class.
You mention django-nonrel in your question tags. That project allows you to use the Django models - subclasses of models.Model with the App Engine datastore. You probably want to do that.
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.
I am trying to use HTSQL for one of my Django projects. For that I followed the procedure given HERE for furnishing HTSQL/Django requirements. Then I cloned the HTSQL repository for trying the example/demo in it from HERE. The default db used in the demo example is sqlite3.
I have tried this demo on both Django v 1.4 and Django v 1.3.1(had to make some tweaks in settings.py for Django v 1.3.1). As instructed in the HTSQL Django-gateway Blog, I wrote the following code in the django project shell:
>>> from htsql_django import produce
>>> query = "/polls_poll{question, total:=sum(polls_choice.votes)}"
>>> for row in produce(query):
>>> print "%s: %s" % (row.question, row.total)
It throws following error:
TransactionManagementError: This code isn't under transaction management
The whole error trace can be viewed at pastebin
I have also tried this on my own new project but same error.
When you use HTSQL from a Django shell, you have to open a transaction explicitly:
>>> from django.db import transaction
>>> from htsql_django import produce
>>> with transaction.commit_on_success():
... query = "/polls_poll{question, total:=sum(polls_choice.votes)}"
... for row in produce(query):
... print "%s: %s" % (row.question, row.total)
I'm sorry the documentation isn't clear about that. We may change it in a future release.
When I query Google AppEngine's datastore using PHP(through Quercus) and the low-level data-access API for an entity, I get an error that the entity doesn't exist, even though I've put it in the datastore previously.
The specific error is "com.caucho.quercus.QuercusException: com.google.appengine.api.datastore.DatastoreService.get: No entity was found matching the key: Test(value1)"
Here's the relevant code -
<?php
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
$testkey = KeyFactory::createKey("Test", "value1");
$ent = new Entity($testkey);
$ent->setProperty("field1", "value2");
$ent->setProperty("field2", "value3");
$dataService = DatastoreServiceFactory::getDatastoreService();
$dataService->put($ent);
echo "Data entered";
try
{
$ent = $dataService->get($testkey);
echo "Data queried - the results are \n";
echo "Field1 has value ".$ent->getProperty("field1")."\n";
echo "Field2 has value ".$ent->getProperty("field2")."\n";
}
catch(EntityNotFoundException $e)
{
echo("<br/>Entity test not found.");
echo("<br/>Stack Trace is:\n");
echo($e);
}
And here's the detailed stack-trace - link.
This same code runs fine in Java (of course after changing the syntax). I wonder what's wrong.
Thanks.
I have found the solution to my problem. It was caused by missing dependencies and I solved it by using the prepackaged PHP Wordpress application available here.
One thing is to be noted. The package overlooked a minor issue in that all files other than the src/ directory need to be in a war/ directory which stays alongside the src/ directory (this as per appengine conventions as mentioned on its documentation). So I organized the files thus myself, put the above PHP file in the war/ directory, and it's working fine on the appengine.