I am using django-pghistory 1.2.0 to keep my changes using postgres triggers. For insert or update, it saves data to event table for both ORM and raw queries. But while using delete, it throws errors.
My model:
#pghistory.track(
pghistory.AfterInsert('after_insert'),
pghistory.AfterUpdate('after_update'),
pghistory.BeforeDelete('before_delete')
)
class TestModel(models.Model):
int_field = models.IntegerField()
char_field = models.CharField(max_length=16)
Error:
psycopg2.errors.ObjectNotInPrerequisiteState: record "new" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())"
PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement
django.db.utils.OperationalError: record "new" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())"
PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement
Test API for CRUD operation:
class TestModelAPI(APIView):
def post(self, request, *args, **kwargs):
obj = TestModel.objects.create(int_field=1, char_field='c1')
obj.int_field = 2
obj.char_field = 'c2'
obj.save()
obj.delete()
return JsonResponse(
data={'message': 'success'},
status=200,
)
My INSTALLED_APPS:
INSTALLED_APPS = [
.............,
'pgtrigger',
'pgconnection',
'pghistory',
]
My database settings:
DATABASES = pgconnection.configure({
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "<some-value>",
"USER": "<some-value>",
"PASSWORD": "<some-value>",
"HOST": "<some-value>",
"PORT": "<some-value>",
},
})
Details error:
Traceback (most recent call last):
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/pgconnection/core.py", line 85, in execute
return super().execute(sql, args)
psycopg2.errors.ObjectNotInPrerequisiteState: record "new" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())"
PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/loan_mngmt_app/api/client_data_api.py", line 88, in post
obj.delete()
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/base.py", line 947, in delete
return collector.delete()
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/deletion.py", line 396, in delete
count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/sql/subqueries.py", line 43, in delete_batch
num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/sql/subqueries.py", line 23, in do_query
cursor = self.get_compiler(using).execute_sql(CURSOR)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql
cursor.execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/pgconnection/core.py", line 85, in execute
return super().execute(sql, args)
django.db.utils.OperationalError: record "new" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())"
PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement
What wrong i have done to configure pghistory.BeforeDelete() of django-pghistory and what is the solution of this problem?
The solution is to use obj_fk=None to pghistory.track()
#pghistory.track(
pghistory.AfterInsert('after_insert'),
pghistory.AfterUpdate('after_update'),
pghistory.BeforeDelete('before_delete'),
obj_fk=None
)
class TestModel(models.Model):
int_field = models.IntegerField()
char_field = models.CharField(max_length=16)
Without obj_fk=None, The trigger will be created where pgh_obj_id column will be present and it will be populated via NEW."id" into trigger's insert statement which raises the error.
CREATE OR REPLACE FUNCTION public.pgtrigger_before_delete_f0f49()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
IF (_pgtrigger_should_ignore(TG_TABLE_NAME, TG_NAME) IS TRUE) THEN
IF (TG_OP = 'DELETE') THEN
RETURN OLD;
ELSE
RETURN NEW;
END IF;
END IF;
INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context());
RETURN NULL;
END;
$function$
;
After using obj_fk=None, you run make migration and migrate command which will remove pgh_obj_id column and NEW."id" from the insert statement.
New statement will be this:
CREATE OR REPLACE FUNCTION public.pgtrigger_before_delete_f0f49()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
IF (_pgtrigger_should_ignore(TG_TABLE_NAME, TG_NAME) IS TRUE) THEN
IF (TG_OP = 'DELETE') THEN
RETURN OLD;
ELSE
RETURN NEW;
END IF;
END IF;
INSERT INTO "loan_mngmt_app_testmodelevent"
("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', _pgh_attach_context());
RETURN NULL;
END;
$function$
;
Related
I am working on a Django/React project. Using DRF, I am throwing an API route for performing SQL queries in my PostgreSQL database. But I am having issues with my current code setup.
I have setup my INSERT query in the API as raw queries (using cursor) enclosed in a triple quote multi-line string """INSERT...""", then format my values using string formatting %s. In my API, I capture each data from the request body into a variable. Everything works fine if all request data are filled. But, if it is null, Django obviously assigns None to the variable.
Now back to my sql query, Django will treat the null %s as None and as a table column instead of a correct null value, thus throwing a ProgrammingError column "none" does not exist.
Here are sample codes:
React Frontend
const [lastName, setLastName] = useState('')
const [firstName, setFirstName] = useState('')
const [middleName, setMiddleName] = useState('')
const [nameExtn, setNameExtn] = useState('')
const [sex, setSex] = useState('')
const [civilStatus, setCivilStatus] = useState('')
const [bloodType, setBloodType] = useState('')
const [height, setHeight] = useState('')
const [weight, setWeight] = useState('')
const newPersonalInfo = (token, data) => {
let endpoint = "/jobnet/api/profile/pds/basic/personal/"
let lookupOptions = {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': `Token ${token}`
},
body: JSON.stringify(data),
credentials: 'include'
}
fetch(endpoint, lookupOptions)
.then(res=>res.json())
.then(function(info){
console.log(info)
})
.catch(err=>console.log(err));
}
const handleNewPersonalInfo = () => {
newPersonalInfo(props.user.token, {
firstname: firstName,
lastname: lastName,
middlename: middleName,
extension: nameExtn,
birthdate: selectedDate,
sex: sex,
civilstatus: civilStatus,
bloodtype: bloodType,
height: height,
weight: weight,
})
}
...
return(
<Button
variant="contained"
color="primary"
onClick={handleNewPersonalInfo}
>
SAVE
</Button>
)
Django API (DRF)
class APIListCreate__PersonalInfo(generics.ListCreateAPIView):
try:
serializer_class = PDSBasicPersonalInfoSerializer
permission_classes = (jobnet_permissions.IsAuthenticated,)
authentication_classes = (knox_TokenAuthentication,)
except Exception as e:
traceback.print_exc()
def get_queryset(self):
user = self.request.user
if user and user.is_authenticated:
query = ("""
SELECT
bsinfo.firstname,
bsinfo.middlename,
bsinfo.surname,
bsinfo.birthdate,
bsinfo.sex,
bsinfo.extention,
bsinfo.civilstatus,
bsinfo.height_m,
bsinfo.weight_kg,
bsinfo.bloodtype,
bsinfo.photo_path
FROM jobnet_app.basicinfo bsinfo
WHERE
id=%s
""" % user.id)
return raw_sql_select(query, "default")
else:
return None
def get(self, request):
data = [
{
"first_name": col.firstname,
"middle_name": col.middlename,
"last_name": col.surname,
"name_extension": col.extention,
"birthdate": col.birthdate,
"sex": col.sex,
"civil_status": col.civilstatus,
"height": col.height_m,
"weight": col.weight_kg,
"blood_type": col.bloodtype,
"photo_path": col.photo_path
} for col in self.get_queryset()[1]
]
return Response(data[0])
def post(self, request):
try:
user = request.user.id
firstname = request.data.get('firstname') or ''
middlename = request.data.get('middlename') or ''
lastname = request.data.get('lastname') or ''
birthdate = request.data.get('birthdate') or ''
sex = request.data.get('sex') or ''
extension = request.data.get('extension') or ''
civilstatus = request.data.get('civilstatus') or ''
height_m = request.data.get('height') or 0
weight_kg = request.data.get('weight') or 0
bloodtype = request.data.get('bloodtype') or ''
query = ("""
START TRANSACTION;
INSERT INTO jobnet_app.basicinfo (
id,
firstname,
middlename,
surname,
birthdate,
sex,
extention,
civilstatus,
height_m,
bloodtype,
weight_kg
)
VALUES (%s,'%s','%s','%s','%s','%s','%s','%s',%s,'%s',%s);
""" % (
user,
firstname,
middlename,
lastname,
birthdate,
sex,
extension,
civilstatus,
height_m,
bloodtype,
weight_kg
)
)
unformatted_query_result = raw_sql_insert(query, "default")
if unformatted_query_result:
raw_sql_commit("default")
return Response({
"success": True,
"message": "Your basic personal information has been updated successfully."
}, status=status.HTTP_201_CREATED)
else:
raw_sql_rollback("default")
return Response({
"success": False,
"message": "There was a problem updating your personal information."
}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
traceback.print_exc()
return Response({
"success": False,
"message":"Internal System Error: " + str(e)
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
With above setup, I get such error:
Traceback (most recent call last):
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 83, in _execute
return self.cursor.execute(sql)
psycopg2.ProgrammingError: column "none" does not exist
LINE 4: ...on','2002-03-18T06:18:45.284Z','Male','','Single',None,'B+',...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\PGADN\Projects\pgadn-v2-website\adnwebsite\reactify\utils.py", line 17, in raw_sql_insert
cn.execute(query)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Acer\Envs\adnwebsite-react\lib\site-packages\django\db\backends\utils.py", line 83, in _execute
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: column "none" does not exist
LINE 4: ...on','2002-03-18T06:18:45.284Z','Male','','Single',None,'B+',...
I am using:
Django 2.0.6
Django Rest Framework 3.10.3
PostgreSQL 11.3 (on my development machine) and PostgreSQL 12.1 (on production server) (although the error above has not yet been replicated to the server)
Note: raw_sql_select, raw_sql_insert, raw_sql_commit, raw_sql_rollback are simply custom-made helper functions which handle the actual cursor execution in the background.
Use SQL Parameters instead of % to create your insert script.
For example-
# **WRONG**
>>> cur.execute("INSERT INTO numbers VALUES (%s, %s)" % (10, 20))
# **correct**
>>> cur.execute("INSERT INTO numbers VALUES (%s, %s)", (10, 20))
You must be using cusrsor.execute in your helper functions. Pass the values as a list as a second parameter in the cusrsor.execute as shown above.
Folow this link to read more.
When trying to query for event documents that match this condition, I'm getting a parsing exception and I'm not sure what's causing it. This is occurring in my custom get_queryset method. In my get_query in my document view set I'm getting an error.
def get_queryset(self):
qs = super().get_queryset()
user = self.request.user
if hasattr(user, 'userprofile'):
user_universities = user.userprofile.universities.all().values_list("id")
user_universities_campus = user.userprofile.universities.all().values_list("main_campus__id")
query = query | Q('bool', must=[
Q('match', visibility_scope=Event.UNIVERSITY),
Q('bool', must=[
Q('terms', university__id=list(user_universities)),
Q('bool', should=[
Q('terms', university__main_campus__id=list(user_universities)),
Q('terms', university__main_campus__id=list(user_universities_campus))
])
])
])
qs = qs.query(query)
return qs
I'm getting this error:
if self.count == 0 and not self.allow_empty_first_page:
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\django\core\paginator.py", line 91, in count
return c()
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch_dsl\search.py", line 679, in count
**self._params
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\client\utils.py", line 84, in _wrapped
return func(*args, params=params, **kwargs)
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\client\__init__.py", line 529, in count
"POST", _make_path(index, doc_type, "_count"), params=params, body=body
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\transport.py", line 358, in perform_request
timeout=timeout,
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 261, in perform_request
self._raise_error(response.status, raw_data)
File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\connection\base.py", line 182, in _raise_error
status_code, error_message, additional_info
elasticsearch.exceptions.RequestError: RequestError(400, 'parsing_exception', '[terms] unknown token [END_ARRAY] after [university.id]')
Query String printout:
Bool(should=[Bool(must=[Match(visibility_scope=2), Bool(must=[Terms(university__id=[(42809,)]), Bool(should=[Terms(university__main_campus__id=[(42809,)]), Terms(university__main_campus__id=[(None,)])])])]), Match(visibility_scope=0)])
Your query in string should be like this:
{
"bool": {
"should":[
"bool" : {
"must":[
{"match":{
"visibility_scope" : 2
},
"bool":{
"must":[
{
"terms": {
}
....
.....
.....
}
]
}
}
]
}
]
}
}
Can you update your question with a querystring? I may be able to complete it.
It is because of queryset. Please set flat=True.
user_universities = user.userprofile.universities.all().values_list("id", flat=True)
I use Django 1.6 and the following error occurred:
Exception happened during processing of request from ('server ip ', 54687)
Traceback (most recent call last):
File "/usr/local/Python2.7.5/lib/python2.7/SocketServer.py", line 593, in process_request_thread
self.finish_request(request, client_address)
File "/usr/local/Python2.7.5/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/local/Python2.7.5/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 126, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/local/Python2.7.5/lib/python2.7/SocketServer.py", line 649, in __init__
self.handle()
File "/usr/local/Python2.7.5/lib/python2.7/wsgiref/simple_server.py", line 124, in handle
handler.run(self.server.get_app())
File "/usr/local/Python2.7.5/lib/python2.7/wsgiref/handlers.py", line 92, in run
self.close()
File "/usr/local/Python2.7.5/lib/python2.7/wsgiref/simple_server.py", line 33, in close
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
I set cookie from client program. Why it happens?
It is client C# of Unity code to create cookie.
Dictionary<string,string> headers = www.responseHeaders;
foreach (KeyValuePair<string,string> kvPair in headers)
{
if (kvPair.Key.ToLower ().Equals ("set-cookie"))
{
string stHeader = "";
string stJoint = "";
string[] astCookie = kvPair.Value.Split (
new string[] {"; "}, System.StringSplitOptions.None);
foreach (string stCookie in astCookie)
{
if (!stCookie.Substring (0, 5).Equals ("path="))
{
stHeader += stJoint + stCookie;
stJoint = "; ";
}
}
if (stHeader.Length > 0)
{
this.hsHeader ["Cookie"] = stHeader;
}
else
{
this.hsHeader.Clear ();
}
}
}
And I set like this
WWW www = new WWW (openURL, null, this.hsHeader);
I think server side is okey.
Because, from browser it runs fine.
stHeader is like this
csrftoken=2YiHLunt9QzqIavUbxfhp2sPVU22g3Vv; expires=Sat, 09-Apr-2016 00:11:19 GMT; Max-Age=31449600
My BackboneJS models now send a GET instead of PUT when I call the model.save() method.
I have a Django back-end with django-tastypie for the REST api.
For example, I have a user model that I try to update like this:
var me = new UserModel({
id: this.user.id
});
me.fetch({
success: function (t) {
console.log(t);
t.set({
'premium': true
});
t.save({
success: function () {
alert('success')
},
error: function (m, e) {
console.log(e);
}
});
}
})
I get the following error in the console:
GET http://127.0.0.1:8000/api/v1/users/100003258103084/ 500 (INTERNAL SERVER ERROR)
in the line where I have t.save()
Is there anything I'm doing wrong here?
EDIT
Alright, the message that it shows int he line console.log(e) is as follow:
"{"error_message": "int() argument must be a string or a number, not 'dict'", "traceback": "Traceback (most recent call last):\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/resources.py\", line 406, in dispatch_detail\n return self.dispatch('detail', request, **kwargs)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/resources.py\", line 427, in dispatch\n response = method(request, **kwargs)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/resources.py\", line 1131, in put_detail\n updated_bundle = self.obj_update(bundle, request=request, **self.remove_api_resource_names(kwargs))\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/resources.py\", line 1827, in obj_update\n m2m_bundle = self.hydrate_m2m(bundle)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/resources.py\", line 743, in hydrate_m2m\n bundle.data[field_name] = field_object.hydrate_m2m(bundle)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/fields.py\", line 742, in hydrate_m2m\n m2m_hydrated.append(self.build_related_resource(value, **kwargs))\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/fields.py\", line 593, in build_related_resource\n return self.resource_from_data(self.fk_resource, value, **kwargs)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/fields.py\", line 548, in resource_from_data\n return fk_resource.obj_update(fk_bundle, **data)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/resources.py\", line 1814, in obj_update\n bundle.obj = self.obj_get(request, **lookup_kwargs)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/tastypie/resources.py\", line 1752, in obj_get\n base_object_list = self.get_object_list(request).filter(**kwargs)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/query.py\", line 621, in filter\n return self._filter_or_exclude(False, *args, **kwargs)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/query.py\", line 639, in _filter_or_exclude\n clone.query.add_q(Q(*args, **kwargs))\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py\", line 1250, in add_q\n can_reuse=used_aliases, force_having=force_having)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py\", line 1185, in add_filter\n connector)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/sql/where.py\", line 69, in add\n value = obj.prepare(lookup_type, value)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/sql/where.py\", line 320, in prepare\n return self.field.get_prep_lookup(lookup_type, value)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.py\", line 137, in get_prep_lookup\n return self._pk_trace(value, 'get_prep_lookup', lookup_type)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.py\", line 210, in _pk_trace\n v = getattr(field, prep_func)(lookup_type, v, **kwargs)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py\", line 310, in get_prep_lookup\n return self.get_prep_value(value)\n\n File \"/home/mohamed/code/skempi/venv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py\", line 537, in get_prep_value\n return int(value)\n\nTypeError: int() argument must be a string or a number, not 'dict'\n"}"
Does this mean that the problem is in Django-Tastypie and not with BackbonejS? Still this GET is the issue i guess!
The save method takes 2 arguments: model.save([attributes], [options]) - both optional.
Right now you are passing the options hash instead of the attributes. Try:
t.save(t.attributes, {
success: function () {
alert('success')
},
error: function (m, e) {
console.log(e);
}
});
or
t.save({'premium':true}, {
success: function () {
alert('success')
},
error: function (m, e) {
console.log(e);
}
});
It seems that me.fetch sends GET request. There is nothing in Backbone that would issue GET request on save unless you have overridden the default sync method.
Save does only POST or PUT requests (POST if model doesn't have id and PUT otherwise).
How would I log errors to django-sentry from celery tasks?
I've tried try: except: blocks and using raven_client.create_from_exception but that blows up every time with:
Traceback (most recent call last):
File "/home/controlpanel/current/env/lib/python2.6/site-packages/celery/execute/trace.py", line 47, in trace
return cls(states.SUCCESS, retval=fun(*args, **kwargs))
File "/home/controlpanel/current/env/lib/python2.6/site-packages/celery/app/task/__init__.py", line 247, in __call__
return self.run(*args, **kwargs)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/celery/app/__init__.py", line 175, in run
return fun(*args, **kwargs)
File "/home/controlpanel/deployments/1323265958/src/deploy/tasks.py", line 60, in async_deploy_bundle
raven_client.create_from_exception(exc_info=exc_info)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/contrib/django/__init__.py", line 120, in create_from_exception
return super(DjangoClient, self).create_from_exception(exc_info, **kwargs)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/base.py", line 285, in create_from_exception
frames = varmap(shorten, get_stack_info(iter_traceback_frames(exc_traceback)))
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/stacks.py", line 128, in get_stack_info
'vars': transform(frame.f_locals.items()),
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in transform
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in <genexpr>
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 72, in <lambda>
transform_rec = lambda o: transform(o, stack + [value], context)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in transform
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in <genexpr>
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 72, in <lambda>
transform_rec = lambda o: transform(o, stack + [value], context)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/raven/utils/encoding.py", line 78, in transform
ret = type(value)(transform_rec(o) for o in value)
File "/home/controlpanel/current/env/lib/python2.6/site-packages/git/util.py", line 588, in __init__
raise ValueError("First parameter must be a string identifying the name-property. Extend the list after initialization")
ValueError: First parameter must be a string identifying the name-property. Extend the list after initialization
My task:
#task
def async_deploy_bundle(bundle_id):
try:
do_stuff(bundle_id)
except:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
try:
raven_client = get_client()
raven_client.create_from_exception(exc_info=exc_info)
except:
pass
raise
What about this:
myLogger = logging.getLogger('mylogger.info')
myLogger.setLevel(logging.INFO)
myLogger.info(exc_info)
?
In my settings.py:
'loggers': {
'mylogger.info': {
'level': 'INFO',
'handlers': ['sentry'],
'propagate': False,
},
}