Django: Django generated sql query causes error - sql

Updated question:
Django is giving me the following sql query:
SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."username" = %s args=('andrew',);
If I execute the sql query in the postgresql command line, I get the following error:
ERROR: syntax error at or near "%"
LINE 1: ..." FROM "auth_user" WHERE "auth_user"."username" = %s args=(...
^
However, when I slightly modify the statement, then I get the cirrect result from postgresql.
SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."username" = 'andrew';
Is the Django generated query incorrect?
Hi Stackoverflow people,
Very simple code which drives me crazy:
I want to extract the user information from user_auth with
user = get_object_or_404(User, pk = request.user.pk)
However, I get an error message in Django:
'NoneType' object does not support item assignment
When I check the sql query and execute it in the psql command line, psql gives me also an error message, which makes me thinking that the statement might be incorrect.
psql statement is:
SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = %s ; args=(7,)
Why does it say %s in the WHERE statement? The user id is not a string.
I believe the solution must be very simple - but I can figure out what the issue is here.
Thank you for your help and suggestions!
Additional explanation
I am using the django_social_auth package for the user authentification. The user will be directed to the dashboard site once the 3rd part cleared the credentials, therefore I would assume that request.user is not None.
Complete traceback
Environment:
Request Method: GET
Request URL: http://login.test.com:8000/profile/dashboard/
Django Version: 1.3.1
Python Version: 2.7.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.gis',
'django.contrib.messages',
'django.contrib.markup',
'django.contrib.staticfiles',
'django.contrib.flatpages',
'django.contrib.humanize',
'guardian',
'easy_thumbnails',
'userena',
'userena.contrib.umessages',
'south',
'django_extensions',
'debug_toolbar',
'social_auth',
'djangoratings',
'about',
'apps.profiles',
'apps.map',
'apps.contact',
]
Installed Middleware:
['django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "/Users/neurix/Development/test/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/neurix/Development/test/test/apps/profiles/views.py" in dashboard
35. extra_context['username'] = user.username
Exception Type: TypeError at /profile/dashboard/
Exception Value: 'NoneType' object does not support item assignment
views.py
...
31: print "user: %s" %(request.user.pk)
32: user = get_object_or_404(User, pk = request.user.pk)
33:
34:
35: extra_context['username'] = user.username
36: if user.first_name:
37: extra_context['name'] = user.first_name
...

Could it be that request.user is None?
if request.user is not None:
user = get_object_or_404(User, pk = request.user.pk)

Related

How to make if else checkbox enabled/disabled in sql query and asp.net?

I want to make my checkbox is enabled and disable when user login from my data
My syntaks in asp.net:
if (Session["Berhasil"] != null)
{
Label1.Visible = true;
Label1.Text = "Berhasil..";
if(Label1 = "select * from cs100020 where countno=2 and status=3");
{
cbxinven.Enabled=true
cbxfinadmin.Enabled=true
cbxkaskecil.Enabled=true
cbxemail.Enabled=false
cbxsap.Enabled=false
cbxpc.Enabled=false
cbxuserad.Enabled=false
}
else (Label1="select * from cs100020 where countno=3 and status=3);
{
cbxinven.Enabled=false
cbxfinadmin.Enabled=false
cbxkaskecil.Enabled=false
cbxemail.Enabled=true
cbxsap.Enabled=true
cbxpc.Enabled=true
cbxuserad.Enabled=true
}
}
and i got error :
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1010: Newline in constant
Source Error:
Line 137: cbxuserad.Enabled=false
Line 138: }
Line 139: else (Label1="select * from cs100020 where countno=3 and status=3);
Line 140: {
Line 141: cbxinven.Enabled=false
Source File: d:\Sharing\Budiman\IAPHRM BACKUP 08022019\IapHRM_180119_Backup\ViewCS.aspx.cs Line: 139
Show Detailed Compiler Output:
Show Complete Compilation Source:
The closing double quote on the SQL statement for the ELSE branch (i.e. else (Label1 = .... line) is missing.

web2py rest api endpoint gives invalid path output

I have made a web2py web application. The api endpoints exposed are as follows.
"/comments[comments]"
"/comments/id/{comments.id}"
"/comments/id/{comments.id}/:field"
"/comments/user-id/{comments.user_id}"
"/comments/user-id/{comments.user_id}/:field"
"/comments/date-commented/{comments.date_commented.year}"
"/comments/date-commented/{comments.date_commented.year}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/{comments.date_commented.minute}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/{comments.date_commented.minute}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/{comments.date_commented.minute}/{comments.date_commented.second}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/{comments.date_commented.minute}/{comments.date_commented.second}/:field"
"/comments/complaint-id/{comments.complaint_id}"
"/comments/complaint-id/{comments.complaint_id}/:field"
The comments model is as follows
models/db.py
db.define_table(
'comments',
Field('user_id', db.auth_user),
Field('comment_made', 'string', length=2048),
Field('date_commented', 'datetime', default=datetime.now),
Field('complaint_id', db.complaints),
Field('detailed_status', 'string', length=2048),
)
I have been successful in retriving a single comment via the following request
localhost:8000/api/comments/id/1.json
Now I wish to retrieve all the comments. I am not able to figure out how to use /comments[comments] to retrieve all comments.?
I have tried
localhost:8000/api/comments.json
But it gives an output with "invalid path"
I have realized requests such as http://localhost:8000/api/comments/complaint-id/1.json
also give "invalid path" as output.
Please help.
EDIT:
Controllers/default.py
#request.restful()
def api():
response.view='generic.' + request.extension
def GET(*args,**kargs):
patterns='auto'
parser = db.parse_as_rest(patterns,args,kargs)
if parser.status == 200:
return dict(content=parser.response)
else:
raise HTTP(parser.status,parser.error)
def POST(*args,**kargs):
return dict()
return locals()
routes.py in the main web2py folder to change the default application:
routers = dict(
BASE = dict(
default_application='GRS',
)
)
Another observation:
I added another endpoint as below:
def comm():
"""" Comments api substitute"""
rows=db().select(db.comments.ALL) ## this line shows error
# rows = db(db.comments.id > 0).select()
#rows=[[5,6],[3,4],[1,2]]
#for row in rows:
# print row.id
return dict(message=rows)
Even now I am not able to retrieve all comments with "/comm.json". This gives a web2py error ticket which says "need more than 1 value to unpack" on the line "rows=db.select(db.comments.ALL)". Are the above invalid path and this error related in someway?

Convert "Opportunity" to "Quotation" error in ODOO / OpenERP

I am developing mobile application for ODOO / OpenERP website in iOS.
I want to convert Opportunity to Quotation in ODOO mobile application ("Convert To Quotation").
For that i am using Model as: "crm.make.sale"
and method as: "makeOrder"
I choose to use above model and method by enabling developer mode. As shown in below screenshot
Below are the input parameters for XMLRPC web-service call:
(
Database name,
1,
Password,
crm.make.sale,
makeOrder,
{
id = 21;
"partner_id" = 12;
}
)
But for above web-service call i am getting error as follow:
invalid input syntax for integer: "partner_id"
LINE 2: ... WHERE "crm_make_sale".id IN ('partner_i...
Where does i am doing wrong ?
Thanks
This might fix your error:
(Database name, 1, Password, crm.make.sale, makeOrder, { 'id': 21; 'partner_id': 12;})

python ldap "Bad search filter" error

This filter works just fine in my LDAP browser by python ldap won't pick it up:
(&(!objectClass=computer)(sn=*%s*))
resulting in:
Request Method: GET Request
URL: http://localhost:8000/ldap_find/%D0%B1%D0%BE%D0%BB%D0%BE%D1%82/
Django Version: 1.4
Exception Type: FILTER_ERROR
Exception Value: {'desc': 'Bad search filter'}
here's the code that does it:
try:
LDAPClient.connect()
base = AUTH_LDAP_SEARCH_BASE
scope = ldap.SCOPE_SUBTREE
filter = '(&(!objectClass=computer)(sn=*%s*))' % search_string
result_set = list()
result = LDAPClient.client.search(base.encode(encoding='utf-8'), scope, filter.encode(encoding='utf-8'),['cn','mail'])
res_type, res_data = LDAPClient.client.result(result)
for data in res_data:
if data[0]:
result_set.append(data)
return json.dumps(result_set)
except Exception, e:
raise e
finally:
LDAPClient.unconnect()
it works fine with simple filters, like
filter = 'sn=*%s*' % search_string
so I'm guessing this is some kind of escaping of & or something inside ldap lib but can't find the root yet.
The search filter syntax is incorrect. Use (&(sn=*%s*)(!(objectClass=computer))). Search filters are well-documented in RFC4511 and RFC4515.

Undefined method 'on' for ActionModel

I'm getting the following error:
NoMethodError in Users#new
Showing .../app/views/users/form/_new.haml where line #7 raised:
undefined method `on' for #<ActiveModel::Errors:0x007fb599ec6610>
The code in line 7 is:
7: = errors_for user, :first_name
And the application_helper.rb:
def errors_for(model, field)
error = case errors = model.errors.on(field)
...
end
'on' is a default method in ActiveRecord. Why doesn't this work?
If you're using Rails 3, then the problem is that there's no "on" method for the Errors class anymore. I think you're supposed to use "get" now. So:
error = case errors = model.errors.get(field)
Or...
error = case errors = model.errors[field]
I checked my user and u.errors is an ActiveRecord::Errors, while I see you have an ActiveModel::Error, I would work on that.
Then I don't understand case errors = statement in your helper, I'm curious to know how you implemented that part...