I have a problem (unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType') with resources involved in foreign key constrains. Here is a piece of code (a contacts belongs to a department and to a client):
class Client(models.Model):
name = models.CharField(max_length=100, unique=True)
address = models.CharField(max_length=100, null=True)
class Department(models.Model):
name = models.CharField(max_length=50, unique=True)
class Contact(models.Model):
name = models.CharField(max_length=50, null=True)
phone = models.CharField(max_length=20, null=True)
email = models.EmailField(max_length=50, null=True)
department = models.ForeignKey(Department)
client = models.ForeignKey(Client)
class BaseResource(ModelResource):
class Meta:
allowed_methods = ['get','post', 'put', 'delete', 'patch']
authorization = Authorization()
abstract = True
class ClientResource(BaseResource):
class Meta(BaseResource.Meta):
queryset = Client.objects.all()
resource_name = 'client'
class DepartmentResource(BaseResource):
class Meta(BaseResource.Meta):
queryset = Department.objects.all()
resource_name = 'department'
class ContactResource(BaseResource):
department = fields.ToOneField(DepartmentResource, 'department', full=True)
client = fields.ToOneField(ClientResource, 'client', full=False)
class Meta(BaseResource.Meta):
queryset = Contact.objects.all()
resource_name = 'contact'
When I try to update a department I haven't got any problem. I do that with:
curl -v -XPATCH -H "Content-Type:application/json" -d "{\"name\": \"Sales\"}" "http://localhost:8000/api/v1/department/1/"
But when I try to do the same in the other resources
curl -v -X PATCH -H "Content-Type:application/json" -d "{\"name\": \"XYZ\"}" "http://localhost:8000/api/v1/client/1/"
returns the following error:
"error_message": "unsupported operand type(s) for ** or pow(): 'Decimal' and NoneType'"
"traceback": "Traceback (most recent call last):
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 406, in dispatch_detail\n return self.dispatch('detail', request, **kwargs)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 427, in dispatch\n response = method(request, **kwargs)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 1332, in patch_detail\n self.update_in_place(request, bundle, deserialized)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 1346, in update_in_place\n return self.obj_update(original_bundle, request=request, pk=original_bundle.obj.pk)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 1824, in obj_update\n bundle.obj.save()
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\base.py\", line 463, in save\n self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\base.py\", line 529, in save_base\n rows = manager.using(using).filter(pk=pk_val)._update(values)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\query.py\", line 557, in _update\n return query.get_compiler(self.db).execute_sql(None)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\sql\\compiler.py\", line 986, in execute_sql\n cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\sql\\compiler.py\", line 808, in execute_sql\n sql, params = self.as_sql()
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\sql\\compiler.py\", line 951, in as_sql\n val = field.get_db_prep_save(val, connection=self.connection)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\fields\\__init__.py\", line 874, in get_db_prep_save\n self.max_digits, self.decimal_places)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\backends\\__init__.py\", line 809, in value_to_db_decimal\n return util.format_number(value, max_digits, decimal_places)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\backends\\util.py\", line 149, in format_number\n return u'%s' % str(value.quantize(decimal.Decimal(\".1\") ** decimal_places, context=context))
TypeError: unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType'\n"}* Closing connection #0
and
curl -v -X PATCH -H "Content-Type:application/json" -d "{\"name\": \"ZZZZ\"}" "http://localhost:8000/api/v1/contact/1/"
returns
The 'department' field has was given data that was not a URI, not a dictionary-alike and does not have a 'pk' attribute: <Bundle for obj: 'Department object' and with data: '{'id': u'1', 'name': u'Sales', 'resource_uri': '/api/v1/department/1/'}'>.* Closing connection #0
I suppose something is wrong in my foreign keys definition but I don't know what. When I do GET operations everything is OK. What is wrong in my definition? Thank you very much.
Related
I want that when creating an account number, the owner of the account be the current logged-in user.
I have read about foreign key constraints but do not know what constraint the CustomUser class is having to conflict the creation of an account number.
I have tried setting on_delete to CASCADE but still it throws the IntegrityError
Please help. Thanks.
My models.py
class CustomUser(TrackingModel, AbstractUser, PermissionsMixin):
GENDER = (
("F", "Female"),
("M", "Male"),
("NS", "Not Specified"),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
phone = models.CharField(max_length=20)
gender = models.CharField(max_length=6, choices=GENDER)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = [
"phone",
]
#property
def token(self):
token = jwt.encode(
{
"username": self.username,
"email": self.email,
"exp": datetime.utcnow() + timedelta(hours=24),
},
settings.SECRET_KEY,
algorithm="HS256",
)
return token
def __str__(self):
return self.username
class Accountnumber(TrackingModel):
TYPE = (
("momo", "MTN Mobile Money"),
("om", "Orange Money"),
("visa", "Visa"),
("paypal", "Paypal"),
)
number = models.AutoField(primary_key=True, editable=False, default=9999)
type = models.CharField(
max_length=10,
choices=TYPE,
null=True,
default="momo",
)
customuser = models.ForeignKey(
CustomUser,
related_name="acc_no_user",
on_delete=models.CASCADE,
)
cdate = models.DateTimeField(auto_now_add=True)
enddate = models.DateTimeField(auto_now_add=True)
transactions = models.ForeignKey(
"Transaction",
related_name="acc_no_transactions",
on_delete=models.CASCADE,
default="2",
)
balance = models.PositiveIntegerField(
null=True,
blank=True,
default=00,
)
def __str__(self):
return self.number
My views.py:
class CreateAccountnumberAPIView(CreateAPIView):
serializer_class = AccountnumberSerializer
permission_classes = {
IsAuthenticated,
}
def perform_create(self, serializer):
return serializer.save(user=self.request.user)
My serializers.py:
class AccountnumberSerializer(serializers.ModelSerializer):
class Meta:
model = Accountnumber
fields = (
"number",
"type",
"cdate",
"enddate",
"transactions",
"balance",
)
My stacktrace shows at perform_create() at views.py:
Internal Server Error: /api/v1/wallet/v1/account
Traceback (most recent call last):
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\utils.py", line 98, in inner
return func(*args, **kwargs)
sqlite3.IntegrityError: FOREIGN KEY constraint failed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\views\generic\base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "C:\Users\USER\Documents\Dev\API\grand\wallet\views.py", line 69, in perform_create
return serializer.save(customuser=self.request.user)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\serializers.py", line
212, in save
self.instance = self.create(validated_data)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\serializers.py", line
962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(),
name)(*args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\base.py", line 806,
in save
self.save_base(
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\base.py", line 857,
in save_base
updated = self._save_table(
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(),
name)(*args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\query.py", line 1434, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\sql\compiler.py", line 1632, in execute_sql
self.connection.ops.fetch_returned_insert_columns(
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\backends\base\operations.py", line 208, in fetch_returned_insert_columns
return cursor.fetchone()
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\utils.py", line 97, in inner
with self:
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\utils.py", line 98, in inner
return func(*args, **kwargs)
django.db.utils.IntegrityError: FOREIGN
KEY constraint failed
[13/Jan/2023 04:19:51] "POST /api/v1/wallet/v1/account HTTP/1.1" 500 183218
In your perform_create function you do the following:
def perform_create(self, serializer):
return serializer.save(user=self.request.user)
So you're saving the user variable to the user that made this request. That is fine, however, in your Accountnumber model, you store the user in the customuser field, not the user field.
Try to set your perform_create function to the following:
def perform_create(self, serializer):
return serializer.save(customuser=self.request.user)
All through, comments from my search for the answer have been that the IntegrityError of ForeignKey constriant failed mostly arises from the fact that you are trying to use a foreign key that does not yet exist and it was my case.
When creating an account number, I asked in my models.py that the field transactions be linked to the Transaction table foreign key WHICH DID NOT EXIST YET.
I, therefore, replaced the transaction field from referring to a ForeignKey to making it a CharField where I used the choices option and it worked.
Thanks, #Pavel Vergeev for editing my code
Thanks, #Ridape for pointing out an error which turns out was not the reason for the IntegrityError I was facing.
I'm trying to fill write the models from shell and i was trying to fill the information for input has ( ForeignKey ) that make it access to another class.
that is my code in pycharm :
class Team(models.Model):
name = models.CharField(max_length=256, unique=True)
details = models.TextField()
def __str__(self):
return self.name
class Player(models.Model):
name = models.CharField(max_length=256)
number = models.IntegerField()
age = models.IntegerField()
position_in_field = models.CharField(max_length=256, choices=(('1', 'حارس'), ('2', 'دفاع'), ('3', 'وسط'), ('4', 'هجوم')))
is_captain = models.BooleanField(default=False)
team = models.ForeignKey(Team)
def __str__(self):
return '{} - {}'.format(self.name, self.team)
and this is the result:
python manage.py shell
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from teams.models import Player
>>> from teams.models import Team
>>> Player.objects.create(name='محمد إبراهيم', number='25', age='27', position_in_field='هجوم', is_captain=False, team='فريق الزمالك')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\query.py", line 392, in create
obj = self.model(**kwargs)
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\base.py", line 555, in __init__
_setattr(self, field.name, rel_obj)
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 216, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "'فريق الزمالك'": "Player.team" must be a "Team" instance.
When you create a record with a foreign key, you have to indicate the record in the referenced model through its primary key.
In the case of model Team, you didn't set a primary key explicitly, so Djangosets de default field mode_id, that is a autoincremental PositiveIntegerField, that is what you have to indicate in the referencing record.
Player.objects.create(name='محمد إبراهيم', number='25', age='27', position_in_field='هجوم', is_captain=False, team_id=1)
If you have a model object with the referenced team, you can use it too:
Player.objects.create(name='محمد إبراهيم', number='25', age='27', position_in_field='هجوم', is_captain=False, team=team_instance)
Good day,
I'm getting the following error: is not JSON serializable
but I'm not sure why am I getting it. Everything was working fine until I decided to start making use of sessions to fire up my user cart adding and removal of items
This is my view:
def add_or_update_cart(request, slug):
request.session.set_expiry(180)
new_total = 0.00
try:
# check that session exists
the_cart_id = request.session['cart_id']
except:
new_cart_id = Cart()
new_cart_id.save()
request.session['cart_id'] = new_cart_id
the_cart_id = new_cart_id.id
cart = Cart.objects.get(id=the_cart_id)
try:
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
pass
except:
pass
if not product in cart.products.all():
cart.products.add(product)
else:
cart.products.remove(product)
for item in cart.products.all():
new_total += float(item.price)
request.session['items_total'] = cart.products.count()
cart.total = new_total
cart.save()
print(cart.products.count())
return HttpResponseRedirect(reverse('cart:cart'))
Models:
class Cart(models.Model):
products = models.ManyToManyField(Product, null=True, blank=True)
total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
cart_status = models.BooleanField(default=False)
def __str__(self):
return '%s' % self.id
def item_name(self):
return " ".join([str(p) for p in self.product.all()])
and in my template:
<li role="presentation">Cart <span class="badge">{{ request.session.items_total }}</span></li>
The traceback:
Internal Server Error: /my-cart/puma/
Traceback (most recent call last):
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/core/handlers/base.py", line 235, in get_response
response = middleware_method(request, response)
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/middleware.py", line 50, in process_response
request.session.save()
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/backends/db.py", line 82, in save
obj = self.create_model_instance(data)
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/backends/db.py", line 68, in create_model_instance
session_data=self.encode(data),
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/backends/base.py", line 88, in encode
serialized = self.serializer().dumps(session_dict)
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/core/signing.py", line 95, in dumps
return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/lib/python3.4/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.4/json/encoder.py", line 173, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Cart: 31> is not JSON serializable
I will appreciate any help on this.
The error arises when Django tries to serialize a model instance here
request.session['cart_id'] = new_cart_id
new_cart_id is a model instance and cannot be serialized.
It seems you wanted to assign the primary key of the instance to the key cart_id.
request.session['cart_id'] = new_cart_id.id
I'm confused. It would seem that Client entity should exist because I have 2 locations for it to be created:
I create the requested Entity in the the setUp() of the unittest.TestCase.
I also conditionally create the Client entity in main.py if it doesn't exist already.
I have tried to set a breakpoint where the Client entity is called, but I can't step into the debugger. While the code stops execution, I can't step into the debugger. I'm not even sure how to see the output.
I set the Consistency policy to 1, so the record should exist.
datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
$ nosetests
INFO 2015-02-24 19:08:56,172 devappserver2.py:726] Skipping SDK update check.
INFO 2015-02-24 19:08:56,242 api_server.py:172] Starting API server at: http://localhost:62049
INFO 2015-02-24 19:08:56,247 dispatcher.py:186] Starting module "default" running at: http://localhost:8080
INFO 2015-02-24 19:08:56,249 admin_server.py:118] Starting admin server at: http://localhost:8000
ERROR 2015-02-24 19:09:00,307 webapp2.py:1552] 'NoneType' object has no attribute 'key'
Traceback (most recent call last):
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/Users/Bryan/work/GoogleAppEngine/dermalfillersecrets/main.py", line 18, in dispatch
webapp2.RequestHandler.dispatch(self)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/Users/Bryan/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/Users/Bryan/work/GoogleAppEngine/dermalfillersecrets/main.py", line 95, in get
self.session['client'] = client.key.urlsafe()
AttributeError: 'NoneType' object has no attribute 'key'
INFO 2015-02-24 19:09:00,314 module.py:737] default: "GET / HTTP/1.1" 500 2354
INFO 2015-02-24 19:09:00,377 module.py:737] default: "GET /favicon.ico HTTP/1.1" 200 8348
INFO 2015-02-24 19:09:00,381 module.py:737] default: "GET /favicon.ico HTTP/1.1" 304 -
EINFO 2015-02-24 19:09:08,482 shutdown.py:45] Shutting down.
INFO 2015-02-24 19:09:08,483 api_server.py:588] Applying all pending transactions and saving the datastore
======================================================================
ERROR: test_guest_can_submit_contact_info (dermalfillersecrets.functional_tests.NewVisitorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/Bryan/work/GoogleAppEngine/dermalfillersecrets/functional_tests.py", line 88, in test_guest_can_submit_contact_info
self.browser.find_element_by_name('id_name').send_keys("Kallie Wheelock")
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 302, in find_element_by_name
return self.find_element(by=By.NAME, value=name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 662, in find_element
{'using': by, 'value': value})['value']
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 173, in execute
self.error_handler.check_response(response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 166, in check_response
raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: Unable to locate element: {"method":"name","selector":"id_name"}
Stacktrace:
at FirefoxDriver.prototype.findElementInternal_ (file:///var/folders/mw/0y88j8_54bjc93d_lg3120qw0000gp/T/tmpSjWZ6W/extensions/fxdriver#googlecode.com/components/driver-component.js:9641:26)
at fxdriver.Timer.prototype.setTimeout/<.notify (file:///var/folders/mw/0y88j8_54bjc93d_lg3120qw0000gp/T/tmpSjWZ6W/extensions/fxdriver#googlecode.com/components/driver-component.js:548:5)
Here is the code in functional_tests.py
import sys, os, subprocess, time, unittest, shlex
sys.path.append("/usr/local/google_appengine")
sys.path.append("/usr/local/google_appengine/lib/yaml/lib")
sys.path.append("/usr/local/google_appengine/lib/webapp2-2.5.2")
sys.path.append("/usr/local/google_appengine/lib/django-1.5")
sys.path.append("/usr/local/google_appengine/lib/cherrypy")
sys.path.append("/usr/local/google_appengine/lib/concurrent")
sys.path.append("/usr/local/google_appengine/lib/docker")
sys.path.append("/usr/local/google_appengine/lib/requests")
sys.path.append("/usr/local/google_appengine/lib/websocket")
sys.path.append("/usr/local/google_appengine/lib/fancy_urllib")
sys.path.append("/usr/local/google_appengine/lib/antlr3")
from selenium import webdriver
from google.appengine.api import memcache, apiproxy_stub, apiproxy_stub_map
from google.appengine.ext import db
from google.appengine.ext import testbed
import dev_appserver
from google.appengine.tools.devappserver2 import devappserver2
class NewVisitorTest(unittest.TestCase):
def setUp(self):
# Start the dev server
cmd = "/usr/local/bin/dev_appserver.py /Users/Bryan/work/GoogleAppEngine/dermalfillersecrets/app.yaml --port 8080 --storage_path /tmp/datastore --clear_datastore --skip_sdk_update_check"
self.dev_appserver = subprocess.Popen(shlex.split(cmd),
stdout=subprocess.PIPE)
time.sleep(2) # Important, let dev_appserver start up
self.testbed = testbed.Testbed()
self.testbed.setup_env(app_id="dev~myapp")
self.testbed.activate()
#self.testbed.setup_env(app_id='dermalfillersecrets')
self.testbed.init_user_stub()
# Create a consistency policy with a probability of 1,
# the datastore should be available.
self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
# Initialize the datastore stub with this policy.
self.testbed.init_datastore_v3_stub(datastore_file="/tmp/datastore/datastore.db", use_sqlite=True, consistency_policy=self.policy)
self.testbed.init_memcache_stub()
self.datastore_stub = apiproxy_stub_map.apiproxy.GetStub('datastore_v3')
# setup the dev_appserver
APP_CONFIGS = ['app.yaml']
# setup client to make sure
from main import Client
if not ( Client.query( Client.name == "Bryan Wheelock").get()):
logging.info("create Admin")
client = Client(
email = "bryan#mail.com",
name = "Bryan Wheelock",
street1 = "555 Main St",
street2 = "unit 1",
city = "Atlanta",
zipcode = 99999,
phone = "(888)555-1212"
).put()
# this sleep is to allow eventual consistency to propogate
time.sleep(2)
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
self.testbed.deactivate()
self.dev_appserver.terminate()
def test_guest_can_submit_contact_info(self):
from main import Client, Customer
client = Client.query( Client.name == "Bryan Wheelock").get()
orig_customer_count = Customer.query(ancestor=client.key).count()
self.browser.get('http://localhost:8080')
time.sleep(5)
self.browser.find_element_by_name('id_name').send_keys("Kallie Wheelock")
self.browser.find_element_by_name('id_street').send_keys("123 main st")
self.browser.find_element_by_name('id_phone').send_keys('(404)555-1212')
self.browser.find_element_by_name('id_zip').send_keys("30306")
self.browser.find_element_by_name('submit').submit()
# the time delay is to allow eventual consisenency to happen.
time.sleep(4)
assert(Customer.query(Customer.name == "Kallie Wheelock").get())
# this should return 1 more record
final_customer_count = Customer.query(ancestor=client.key).count()
self.assertNotEqual(orig_customer_count, final_customer_count)
# Delete the Customer record
Customer.query(Customer.name =="Kallie Wheelock").delete()
Here's the code in main.py:
import os
import urllib
import logging
from google.appengine.api import users
from google.appengine.ext import ndb
import jinja2
import webapp2
from webapp2_extras import sessions
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
# dispatch the request
webapp2.RequestHandler.dispatch(self)
finally:
# save all sessions
self.session_store.save_sessions(self.response)
#webapp2.cached_property
def session(self):
# Returns a session using the default cookie key.
return self.session_store.get_session()
JINJA_ENVIRONMENT = jinja2.Environment(
loader = jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
DEFAULT_LEADBOOK_NAME = 'whatsmyname'
def leadbook_key(leadbook_name=DEFAULT_LEADBOOK_NAME):
"""Constructs a Datastore key for a LeadBook entity with leadbook_name."""
return ndb.Key('LeadBook', leadbook_name)
class Client(ndb.Model):
email = ndb.StringProperty()
name = ndb.StringProperty(indexed=True)
street1 = ndb.StringProperty()
street2 = ndb.StringProperty()
city = ndb.StringProperty()
zipcode = ndb.IntegerProperty()
phone = ndb.StringProperty()
signup = ndb.DateTimeProperty(auto_now_add=True)
# this just creates a Client to use
if not ( Client.query( Client.name == "Bryan Wheelock").get()):
client = Client(
email = "bryan#mail.com",
name = "Bryan Wheelock",
street1 = "555 Main St",
street2 = "unit 1",
city = "Atlanta",
zipcode = 99999,
phone = "(888)555-1212"
).put()
class Customer(ndb.Model):
# I commented out client property because using Ancestor Query( limited to 1 write per second)
#client = ndb.KeyProperty(kind=Client)
#email = ndb.StringProperty(indexed=True)
name = ndb.StringProperty(indexed=True)
street1 = ndb.StringProperty()
street2 = ndb.StringProperty()
city = ndb.StringProperty()
zipcode = ndb.IntegerProperty()
phone = ndb.StringProperty()
signup = ndb.DateTimeProperty(auto_now_add=True)
class MainPage(BaseHandler):
def get(self):
leadbook_name = self.request.get('leadbook_name',
DEFAULT_LEADBOOK_NAME)
# This record should exist because I create in setUP and in main.py
client = Client.query( Client.name == "Bryan Wheelock").get()
###########################################################
########################
# I can't step into the debugger because I don't know how to access debugger shell.
import pdb; pdb.set_trace()
########################
###########################################################
self.session['client'] = client.key.urlsafe()
template_values = {
'client': client,
'leadbook_name': urllib.quote_plus(leadbook_name),
}
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
class LeadBook(BaseHandler):
def post(self):
leadbook_name = self.request.get('leadbook_name',
DEFAULT_LEADBOOK_NAME)
client = ndb.Key(urlsafe=self.session['client']).get()
customer = Customer( parent = client.key)
customer.name = self.request.get('id_name')
customer.street1 = self.request.get('id_street')
customer.phone = self.request.get('id_phone')
customer.zipcode = int(self.request.get('id_zip'))
# show original number of customer to show the code works
starting_customer_count = Customer.query(ancestor=client.key).count()
customer.put()
# This should return the record
assert(Customer.query(Customer.name == "Kallie Wheelock").get())
final_customer_count = Customer.query(ancestor=client.key).count()
#import pdb; pdb.set_trace()
query_params = {'leadbook_name': leadbook_name}
self.redirect('/?' + urllib.urlencode(query_params))
config = {}
config['webapp2_extras.sessions'] = {
'secret_key': 'my-super-secret-key',
}
application = webapp2.WSGIApplication([
('/', MainPage),
('/sign', LeadBook),
], config = config,
debug=True)
Considering you use nosetests, try running it with the pdb option.
nosetests -sv --pdb
The --pdb option will drop the test runner into pdb when it encounters an error.
More info here:
http://nose.readthedocs.org/en/latest/plugins/debug.html
I asked my question in appropriate Google Group (http://groups.google.com/group/django-non-relational/browse_thread/thread/a51c1903af175e1c), but developers seems are kinda busy now, so I'm afraid my question will remain unanswered. Hope I'll find solution of my problem here.
Essense is:
I use Django-nonrel + GAE + Blog App from Django Basic apps
From admin panel of my app I tried to create new blog post. And got the following exception:
DatabaseError: Lookup type 'month' isn't supported
I asked about this in related google group and was answered to use django-dbindexer.
Regarding it desription it is exactly what I need, so I guided through all instructions and "attached" it to my app. Indexing is done, but I however get the same exception. Here is the full trace:
Traceback (most recent call last):
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\core\handlers\base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\contrib\admin\options.py", line 308, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\utils\decorators.py", line 93, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\views\decorators\cache.py", line 79, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\contrib\admin\sites.py", line 190, in inner
return view(request, *args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\utils\decorators.py", line 28, in _wrapper
return bound_func(*args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\utils\decorators.py", line 93, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\utils\decorators.py", line 24, in bound_func
return func(self, *args2, **kwargs2)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\transaction.py", line 282, in inner
res = func(*args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\contrib\admin\options.py", line 852, in add_view
if form.is_valid():
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\forms.py", line 121, in is_valid
return self.is_bound and not bool(self.errors)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\forms.py", line 112, in _get_errors
self.full_clean()
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\forms.py", line 269, in full_clean
self._post_clean()
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\models.py", line 338, in _post_clean
self.validate_unique()
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\models.py", line 347, in validate_unique
self.instance.validate_unique(exclude=exclude)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\models\base.py", line 669, in validate_unique
date_errors = self._perform_date_checks(date_checks)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\models\base.py", line 791, in _perform_date_checks
if qs.exists():
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\models\query.py", line 498, in exists
return self.query.has_results(using=self.db)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\models\sql\query.py", line 428, in has_results
return compiler.has_results()
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 222, in has_results
return self.get_count(check_exists=True)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 269, in get_count
return self.build_query().count(high_mark)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 275, in build_query
query.add_filters(self.query.where)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 72, in add_filters
self.add_filters(child)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 76, in add_filters
self.add_filter(column, lookup_type, self._negated, db_type, value)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangoappengine\db\compiler.py", line 57, in _func
return func(*args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangoappengine\db\compiler.py", line 211, in add_filter
raise DatabaseError("Lookup type %r isn't supported" % lookup_type)
DatabaseError: Lookup type 'month' isn't supported
Here is my data model (from basic.blog.models):
class Post(models.Model):
"""Post model."""
STATUS_CHOICES = (
(1, _('Draft')),
(2, _('Public')),
)
title = models.CharField(_('title'), max_length=200)
slug = models.SlugField(_('slug'), unique_for_date='publish')
author = models.ForeignKey(User, blank=True, null=True)
body = models.TextField(_('body'), )
tease = models.TextField(_('tease'), blank=True, help_text=_('Concise text suggested. Does not appear in RSS feed.'))
status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=2)
allow_comments = models.BooleanField(_('allow comments'), default=True)
publish = models.DateTimeField(_('publish'), default=datetime.datetime.now)
created = models.DateTimeField(_('created'), auto_now_add=True)
modified = models.DateTimeField(_('modified'), auto_now=True)
categories = models.ManyToManyField(Category, blank=True)
tags = TagField()
objects = PublicManager()
class Meta:
verbose_name = _('post')
verbose_name_plural = _('posts')
db_table = 'blog_posts'
ordering = ('-publish',)
get_latest_by = 'publish'
def __unicode__(self):
return u'%s' % self.title
#permalink
def get_absolute_url(self):
return ('blog_detail', None, {
'year': self.publish.year,
'month': self.publish.strftime('%b').lower(),
'day': self.publish.day,
'slug': self.slug
})
def get_previous_post(self):
return self.get_previous_by_publish(status__gte=2)
def get_next_post(self):
return self.get_next_by_publish(status__gte=2)
Here is what I have in dbindexes module of my app (basic.blog.dbindexes):
from basic.blog.models import Post
from dbindexer.api import register_index
register_index(Post, {
'publish': 'month',
# 'created': 'month',
# 'modified': 'month',
})
import logging
logger = logging.getLogger(__name__)
logger.info('Basic.blog dbindexes') # Logging statement to check if this module is ever executed to be sure indexing is done
Thanks in advance for any help.