I have two models which are as follows:
class PostUser(models.Model):
user_id = models.CharField(max_length=1000,blank=True,null=True)
reputation = models.CharField(max_length = 1000 , blank = True , null = True)
def __unicode__(self):
return self.user_id
def indexing(self):
obj = PostUserIndex(
meta = {'id': self.id},
user_id = self.user_id,
reputation = self.reputation,
)
obj.save(index = 'post-user-index')
return obj.to_dict(include_meta=True)
class Posts(models.Model):
user_post_id = models.CharField(max_length = 1000 , blank = True , null = True)
score = models.CharField(max_length = 1000 , blank = True , null = True)
owner_user_id = models.ForeignKey(PostUser,default="-100")
def __unicode__(self):
return self.user_post_id
def indexing(self):
obj = PostsIndex(
meta = {'id': self.id},
user_post_id = self.user_post_id,
score = self.score,
owner_user_id = self.owner_user_id,
)
obj.save(index = 'newuserposts-index')
return obj.to_dict(include_meta=True)
The way I am trying to index my data is as follows:
class PostUserIndex(DocType):
user_id = Text()
reputation = Text()
class PostsIndex(DocType):
user_post_id = Text()
score = Text()
owner_user_id = Nested(PostUserIndex)
Then i try to run the following method to index data:
def posts_indexing():
PostsIndex.init(index='newuserposts-index')
es = Elasticsearch()
bulk(client=es, actions=(b.indexing() for b in models.Posts.objects.all().iterator()))
I have tried different approaches by manually entering the nested properties and also changing from doctype to inner doc of PostUser but still I am getting the weird error.
ERROR:
AttributeError: 'PostUser' object has no attribute 'copy'
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/ammarkhan/Desktop/danny/src/dataquerying/datatoindex.py", line 74, in new_user_posts_indexing
bulk(client=es, actions=(b.indexing() for b in models.Posts.objects.all().iterator()))
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 257, in bulk
for ok, item in streaming_bulk(client, actions, **kwargs):
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 180, in streaming_bulk
client.transport.serializer):
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 58, in _chunk_actions
for action, data in actions:
File "/Users/ammarkhan/Desktop/danny/src/dataquerying/datatoindex.py", line 74, in <genexpr>
bulk(client=es, actions=(b.indexing() for b in models.Posts.objects.all().iterator()))
File "/Users/ammarkhan/Desktop/danny/src/dataquerying/models.py", line 167, in indexing
obj.save(index = 'newuserposts-index')
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch_dsl/document.py", line 405, in save
self.full_clean()
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch_dsl/utils.py", line 417, in full_clean
self.clean_fields()
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch_dsl/utils.py", line 403, in clean_fields
data = field.clean(data)
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch_dsl/field.py", line 179, in clean
data = super(Object, self).clean(data)
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch_dsl/field.py", line 90, in clean
data = self.deserialize(data)
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch_dsl/field.py", line 86, in deserialize
return self._deserialize(data)
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch_dsl/field.py", line 166, in _deserialize
return self._wrap(data)
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch_dsl/field.py", line 142, in _wrap
return self._doc_class.from_es(data)
File "/Users/ammarkhan/Desktop/danny/lib/python2.7/site-packages/elasticsearch_dsl/utils.py", line 342, in from_es
meta = hit.copy()
AttributeError: ‘PostUser' object has no attribute 'copy'
You are calling .save in your indexing methods which will save the document to elasticsearch and then you are also passing it to bulk to accomplish the same, the save is extra.
You are also assigning an instance of PostUser to owner_user_id instead of properly serializing it by calling the indexing method on it (without the save inside):
def indexing(self):
obj = PostsIndex(
meta = {'id': self.id, 'index': 'newuserposts-index'},
user_post_id = self.user_post_id,
score = self.score,
owner_user_id = self.owner_user_id.indexing(),
)
return obj.to_dict(include_meta=True)
Related
My database stores bool values as CHAR(1), T=True, F=False. I'm trying to write a converter so that I can use bool values in my python code and have pony handle the conversion to the database.
Here's what I have:
from pony import orm
from pony.orm.dbapiprovider import BoolConverter
class DALBoolConverter(BoolConverter):
def validate(self, val, obj=None):
print 'VALIDATOR', val, obj
return val
def py2sql(self, val):
print 'py2sql', val
return 'T' if val else 'F'
def sql2py(self, val):
print 'sql2py', val
return True if val == 'T' else False
def sql_type(self):
print 'sql_type'
return 'CHAR(1)'
db.provider.converter_classes.append((bool, DALBoolConverter))
class AuthUser(db.Entity):
_table_ = 'auth_user'
first_name = orm.Required(str)
last_name = orm.Required(str)
email = orm.Optional(str)
password = orm.Optional(str)
registration_key = orm.Optional(str)
reset_password_key = orm.Optional(str)
registration_id = orm.Optional(str)
active = orm.Required(bool)
if __name__ == '__main__':
with db_session:
a = AuthUser[1]
print a.active # returns True
a.active = False
You can see I have some print statements in there but they are never executed. I'm getting the following traceback:
Traceback (most recent call last):
File "/home/jim/dev/qlf/qlf/pony_model.py", line 720, in <module>
"""
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 476, in __exit__
db_session._commit_or_rollback(exc_type, exc, tb)
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 490, in _commit_or_rollback
commit()
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 381, in commit
rollback_and_reraise(sys.exc_info())
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 370, in rollback_and_reraise
reraise(*exc_info)
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 379, in commit
cache.flush()
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 1888, in flush
if obj is not None: obj._save_()
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 5363, in _save_
elif status == 'modified': obj._save_updated_()
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 5272, in _save_updated_
cursor = database._exec_sql(sql, arguments, start_transaction=True)
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 945, in _exec_sql
connection = cache.reconnect(e)
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 1776, in reconnect
if not provider.should_reconnect(exc): reraise(*sys.exc_info())
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/core.py", line 943, in _exec_sql
try: new_id = provider.execute(cursor, sql, arguments, returning_id)
File "<auto generated wrapper of execute() function>", line 2, in execute
File "/home/jim/.local/lib/python2.7/site-packages/pony/orm/dbapiprovider.py", line 61, in wrap_dbapi_exceptions
raise OperationalError(e)
pony.orm.dbapiprovider.OperationalError: (1292, "Truncated incorrect DOUBLE value: 'T '")
...which probably makes sense because I don't think my DALBoolConverter is ever getting called.
Any pointers?
Easiest way to achieve your goal is to use hybrid methods.
So you do
class AuthUser(db.Entity):
_table_ = 'auth_user'
first_name = orm.Required(str)
last_name = orm.Required(str)
email = orm.Optional(str)
password = orm.Optional(str)
registration_key = orm.Optional(str)
reset_password_key = orm.Optional(str)
registration_id = orm.Optional(str)
active = orm.Required(str) # use str here
#property
def is_active(self):
return self.active == 'T'
Then you might use
with db_session:
a = AuthUser[1]
print a.is_active
This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed 5 years ago.
model in my application:
from __future__ import unicode_literals
from django.db import models
class Category(models.Model):
name = models.CharField(max_length = 128, unique = True)
def __unicode__(self):
return self.name
class ModelName(models.Model):
name = models.CharField(max_length = 128, unique = True)
def __unicode__(self):
return self.name
class CarStorage(models.Model):
category = models.ForeignKey(Category)
CarID = models.CharField(max_length = 10, unique = True, null = False)
model = models.ForeignKey(ModelName)
storage = models.IntegerField(default = 0)
perchasedYear = models.IntegerField(default = 0)
def __unicode__(self):
return self.CarID
Population code:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','TKTrading.settings')
import django
django.setup()
from APP.models import Category, ModelName, CarStorage
def populate():
BASE_DIR = '/Users/apple/WebWorkshop/TKTrading/'
DATA_DIR = os.path.join(BASE_DIR, 'APP/Data')
CATEGORY = open(os.path.join(DATA_DIR, 'CATEGORY.txt'),'r')
global CategoryList
CategoryList = []
for line in CATEGORY:
newC = Add_Category(line)
CategoryList.append(newC)
CATEGORY.close
MODELNAME = open(os.path.join(DATA_DIR, 'Model.txt'), 'r')
global ModelList
ModelList = []
for line2 in MODELNAME:
newM = Add_ModelName(line2)
ModelList.append(newM)
MODELNAME.close
CARSTORAGE = open(os.path.join(DATA_DIR, 'CARSTORAGE.txt'), 'r')
for line3 in CARSTORAGE:
print(line3)
c = line3.split(',')
ID = str(c[0])
category = str(c[1])
model = str(c[2])
storage = int(c[3])
year = int(c[4])
Add_CarStorage(ID, category, model, storage, year)
CARSTORAGE.close
def Add_Category(name):
c = Category.objects.get_or_create(name = name)[0]
c.save()
return c
def Add_ModelName(name):
m = ModelName.objects.get_or_create(name = name)[0]
m.save()
return m
def Add_CarStorage(ID, category, model, storage, year):
for CATEGORY in CategoryList:
if CATEGORY.name == category:
category = CATEGORY
for MODEL in ModelList:
if MODEL.name == model:
model = MODEL
car = CarStorage.objects.get_or_create(CarID = ID,
category = category,
model = model,)[0]
car.storage = storage
car.perchasedYear = year
car.save()
return car
if __name__ =='__main__':
print('Starting population...')
populate()
For the population code, I have try two way but got the same message.
One is put all the category and model in a list as object, the other one is using string to create new object directly.
In the end this is the whole message feedback:
Traceback (most recent call last):
File "DBPopulation.py", line 77, in <module>
populate()
File "DBPopulation.py", line 45, in populate
Add_CarStorage(ID, category, model, storage, year)
File "DBPopulation.py", line 69, in Add_CarStorage
model = model,)[0]
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 471, in get_or_create
return self.get(**lookup), False
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 376, in get
clone = self.filter(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 794, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 812, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1227, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1253, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1183, in build_filter
condition = lookup_class(lhs, value)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/lookups.py", line 19, in __init__
self.rhs = self.get_prep_lookup()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/related_lookups.py", line 100, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 946, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'Wing'
TXT file:
2512-305,Wing,Nissan UD,10,2003
2010-41,Wing,Hino,4,1997
2607-312,Cargo Drop Side,Isuzu,6,2012
2411-341,Cargo Drop Side,Nissan UD,7,2000
2406-326,Tractor,Nissan UD,12,1996
2211-101,Other,Komatsu,1,0
I understand there might have problems like putting string or nothing in the integer field, but I have reread many time and still not figure out.
The problem is with your Add_CarStorage function.
when
if MODEL.name == model:
is true you are replacing string model with MODEL which is a ModelName instance but when the condition is false you are not updating the variable model with anything. A quick fix would be to use get_or_create call only when the condition is true.
I need help again. Can anybody tell my why I get this error? I use Flask and pony orm and python 3.4. I have few files.
users.py
from app import models
from pony.orm import *
class UsersAPI:
#staticmethod
#db_session
def is_registered(e_mail):
"""
This method for checking registered user or not
:param e_mail:
:return:
"""
user = select(o for o in models.Users if o.email == e_mail)[:]
print(user)
UsersAPI.is_registered("evgenusov96#yandex.ru")
File models.py
from pony.orm import *
import config
db = Database()
class Users(db.Entity):
id = PrimaryKey(int, auto=True)
email = Required(str, 100)
password = Required(str, 32)
name = Required(str, 15)
surname = Required(str, 20)
city = Required(City, nullable=True)
sex = Required(int)
request = Required(str, 250, nullable=True)
hobby = Required(str, 250, nullable=True)
about = Required(str, 250, nullable=True)
status_message = Required(str, 100, nullable=True)
user1 = Set("Friends", reverse="user1")
user2 = Set("Friends", reverse="user2")
author = Set("Messages", reverse="author")
addressee = Set("Messages", reverse="addressee")
This error I got:
C:\Python34\python.exe C:/Users/Евгений/PycharmProjects/langunet/run.py
Traceback (most recent call last):
File "C:/Users/Евгений/PycharmProjects/langunet/run.py", line 2, in <module>
from app import app
File "C:\Users\Евгений\PycharmProjects\langunet\app\__init__.py", line 4, in <module>
from app import routes
File "C:\Users\Евгений\PycharmProjects\langunet\app\routes.py", line 2, in <module>
from app.users import *
File "C:\Users\Евгений\PycharmProjects\langunet\app\users.py", line 21, in <module>
UsersAPI.is_registered("evgenusov96#yandex.ru")
File "<string>", line 2, in is_registered
File "C:\Python34\lib\site-packages\pony\orm\core.py", line 347, in new_func
try: return func(*args, **kwargs)
File "C:\Users\Евгений\PycharmProjects\langunet\app\users.py", line 18, in is_registered
user = get(o for o in models.Users if o.email == e_mail)
File "<string>", line 2, in get
File "C:\Python34\lib\site-packages\pony\utils.py", line 88, in cut_traceback
return func(*args, **kwargs)
File "C:\Python34\lib\site-packages\pony\orm\core.py", line 4260, in get
return make_query(args, frame_depth=3).get()
File "<string>", line 2, in get
File "C:\Python34\lib\site-packages\pony\utils.py", line 88, in cut_traceback
return func(*args, **kwargs)
File "C:\Python34\lib\site-packages\pony\orm\core.py", line 4531, in get
objects = query[:2]
File "<string>", line 2, in __getitem__
File "C:\Python34\lib\site-packages\pony\utils.py", line 88, in cut_traceback
return func(*args, **kwargs)
File "C:\Python34\lib\site-packages\pony\orm\core.py", line 4721, in __getitem__
return query._fetch(range=(start, stop))
File "C:\Python34\lib\site-packages\pony\orm\core.py", line 4426, in _fetch
used_attrs=translator.get_used_attrs())
File "C:\Python34\lib\site-packages\pony\orm\core.py", line 3228, in _fetch_objects
real_entity_subclass, pkval, avdict = entity._parse_row_(row, attr_offsets)
File "C:\Python34\lib\site-packages\pony\orm\core.py", line 3258, in _parse_row_
avdict[attr] = attr.parse_value(row, offsets)
File "C:\Python34\lib\site-packages\pony\orm\core.py", line 1329, in parse_value
val = attr.validate(row[offset], None, attr.entity, from_db=True)
File "C:\Python34\lib\site-packages\pony\orm\core.py", line 1611, in validate
if obj is None: throw(ValueError, 'Attribute %s is required' % attr)
File "C:\Python34\lib\site-packages\pony\utils.py", line 126, in throw
raise exc
ValueError: Attribute Users.request is required
How this may to fix? Thank you!
This error can happen if you defined User.request attribute as Required, but in the table the corresponding column is actually optional (that is, nullable). During loading of an object, Pony checks if the object's internal state is consistent. Since the value of a required attribute is missed, Pony generates an exception.
I think that we need to improve Pony behavior in one of two ways here:
Even if an attribute is required, Pony should allow loading of null values for this attribute from the database.
Another alternative is to make error message more clear.
I am trying to define models in Django with a list of embedded documents using mongoengine to connect to my mongodb data. Here is the relevant part of my models.py:
class Feature(EmbeddedDocument):
title = StringField(max_length=100, required=True)
is_property = BooleanField(default=True)
property_type = StringField(max_length=50, choices=PROPERTY_TYPE)
def __unicode__(self):
return self.title or u''
class Property(EmbeddedDocument):
feature = EmbeddedDocumentField(Feature)
value = StringField(max_length=2000, required=True)
def __unicode__(self):
return self.feature
class Concept(Document):
title = StringField(max_length=200, required=True)
properties = ListField(EmbeddedDocumentField(Property))
In console, when I try to create a new Concept, i do the following:
f = Feature(title='start time',property_type='Time')
p = Property(feature=f, value='6:30pm')
c = Concept(title='test', properties = [p])
c.save() #or c.properties[0]
I then get the following error:
c.properties
Out[36]: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2731, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-36-47a09d2ccd39>", line 1, in <module>
c.properties
File "/usr/lib/python2.7/dist-packages/IPython/core/displayhook.py", line 238, in __call__
format_dict = self.compute_format_data(result)
File "/usr/lib/python2.7/dist-packages/IPython/core/displayhook.py", line 150, in compute_format_data
return self.shell.display_formatter.format(result)
File "/usr/lib/python2.7/dist-packages/IPython/core/formatters.py", line 126, in format
data = formatter(obj)
File "/usr/lib/python2.7/dist-packages/IPython/core/formatters.py", line 447, in __call__
printer.pretty(obj)
File "/usr/lib/python2.7/dist-packages/IPython/lib/pretty.py", line 345, in pretty
return self.type_pprinters[cls](obj, self, cycle)
File "/usr/lib/python2.7/dist-packages/IPython/lib/pretty.py", line 529, in inner
p.pretty(x)
File "/usr/lib/python2.7/dist-packages/IPython/lib/pretty.py", line 360, in pretty
return _default_pprint(obj, self, cycle)
File "/usr/lib/python2.7/dist-packages/IPython/lib/pretty.py", line 480, in _default_pprint
p.text(repr(obj))
File "/usr/local/lib/python2.7/dist-packages/mongoengine-0.8.6-py2.7.egg/mongoengine/base/document.py", line 201, in __repr__
u = self.__str__()
File "/usr/local/lib/python2.7/dist-packages/mongoengine-0.8.6-py2.7.egg/mongoengine/base/document.py", line 212, in __str__
return unicode(self).encode('utf-8')
TypeError: coercing to Unicode: need string or buffer, Feature found
I think you need to explicitly convert the Feature to unicode, because mongoengine calls .encode on the __unicode__ of your object:
return unicode(self).encode('utf-8')
Where self is an instance of Property, and unicode(self) would return your Feature instance. So something like this should work
class Property(...):
# ...
def __unicode__(self):
return unicode(self.feature)
I am making a web service in Web2Py which accept some parameters and inserts them into a table. I am getting the following error while I am inserting data in this 1 table
Traceback (most recent call last):
File "E:\Development\Python\web2py\gluon\restricted.py", line 192, in restricted
exec ccode in environment
File "E:/Development/Python/web2py/applications/my_app/controllers/mobi.py", line 96, in <module>
File "E:\Development\Python\web2py\gluon\globals.py", line 145, in <lambda>
self._caller = lambda f: f()
File "E:/Development/Python/web2py/applications/my_app/controllers/mobi.py", line 81, in createwish
wish_id = db.t_wish.insert(f_user_id = id, f_category_id = category_id, f_sub_category_id = sub_category_id, f_min_price = min_price, f_max_price = max_price, f_location_range = location_range, f_keywords = keywords)
File "E:\Development\Python\web2py\gluon\dal.py", line 4786, in insert
return self._db._adapter.insert(self,self._listify(fields))
File "E:\Development\Python\web2py\gluon\dal.py", line 838, in insert
query = self._insert(table,fields)
File "E:\Development\Python\web2py\gluon\dal.py", line 834, in _insert
values = ','.join(self.expand(v,f.type) for f,v in fields)
File "E:\Development\Python\web2py\gluon\dal.py", line 834, in <genexpr>
values = ','.join(self.expand(v,f.type) for f,v in fields)
File "E:\Development\Python\web2py\gluon\dal.py", line 951, in expand
return self.represent(expression,field_type)
File "E:\Development\Python\web2py\gluon\dal.py", line 1266, in represent
obj = obj()
TypeError: id() takes exactly one argument (0 given)
The model is this
########################################
db.define_table('t_wish',
Field('id','id',
represent=lambda id:SPAN(id,' ',A('view',_href=URL('wish_read',args=id)))),
Field('f_user_id', type='string',
label=T('User Id')),
Field('f_category_id', type='string',
label=T('Category Id')),
Field('f_sub_category_id', type='string',
label=T('Sub Category Id')),
Field('f_min_price', type='integer',
label=T('Min Price')),
Field('f_max_price', type='integer',
label=T('Max Price')),
Field('f_location_range', type='integer',
label=T('Location Range')),
Field('f_keywords', type='string',
label=T('Keywords')),
Field('is_active','boolean',default=True,
label=T('Active'),writable=False,readable=False),
Field('created_on','datetime',default=request.now,
label=T('Created On'),writable=False,readable=False),
Field('modified_on','datetime',default=request.now,
label=T('Modified On'),writable=False,readable=False,
update=request.now),
Field('created_by',db.auth_user,default=auth.user_id,
label=T('Created By'),writable=False,readable=False),
Field('modified_by',db.auth_user,default=auth.user_id,
label=T('Modified By'),writable=False,readable=False,
update=auth.user_id),
format='%(f_user_id)s',
migrate=settings.migrate)
db.define_table('t_wish_archive',db.t_wish,Field('current_record','reference t_wish'))
Code to insert the data is this
#Creating a wish
def createwish():
try:
user_id = request.vars['id']
category_id = request.vars['category_id']
sub_category_id = request.vars['sub_category_id']
min_price = request.vars['min_price']
max_price = request.vars['max_price']
location_range = request.vars['loc_range']
keywords = request.vars['keywords']
except:
raise HTTP(400, 'BAD REQUEST: Requires all params - id, category_id, sub_category_id, min_price, max_price, loc_range, keywords')
# try:
wish_id = db.t_wish.insert(f_user_id = id, f_category_id = category_id, f_sub_category_id = sub_category_id, f_min_price = min_price, f_max_price = max_price, f_location_range = location_range, f_keywords = keywords)
return sj.dumps({'result':'success', 'wish_id':wish_id})
#except:
# raise HTTP(500, 'Internal Server Error')
Any ideas?
You have problems here:
db.define_table('t_wish',
Field('id','id',
represent=lambda id:SPAN(id,' ',A('view',_href=URL('wish_read',args=id)))),
and here:
# try:
wish_id = db.t_wish.insert(f_user_id = id, ...)
change to:
db.define_table('t_wish',
Field('id','id',
represent=lambda value:SPAN(value,' ',A('view',_href=URL('wish_read',args=id)))),
and
# try:
wish_id = db.t_wish.insert(f_user_id = user_id, ....)
You cannot use 'id' because it is a Python built in
File "E:/Development/Python/web2py/applications/my_app/controllers/mobi.py", line 81, in createwish
wish_id = db.t_wish.insert(f_user_id = id, f_category_id = category_id, f_sub_category_id = sub_category_id, f_min_price = min_price, f_max_price = max_price, f_location_range = location_range, f_keywords = keywords)
Note the f_user_id = id, that's the python builtin. I'm assuming you mean some other variable.