def insertCompany_type(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
c_type = data["subject"]
user = get_user_id(request)
print user
c_ty=Company_Type(user_id=user,type=c_type)
c_ty.save(force_insert=True)
except:
print 'nope'
return JsonResponse({'status': 'success'})
print user
displays [{'user_id': 1L}]
.. How can i assign 1 to user_id
in Company_Type(user_id=user,type=c_type)
for creating objects
When you actually make a user (which doesnt happen your snippet of code) you can pass a constuctor argument setting user_id. eg
myUser = User(name="shalin", user_id=1)
myUser.save()
Also, you can get user objects from requests simply by doing this:
user = request.user
which is a bit easier than what you're doing I think.
If user is a list of length 1, containing a dict, you can extract the value of a dict as follows:
value = user[0]['user_id']
You could modify your code as:
if request.method == 'POST':
try:
data = json.loads(request.body)
c_type = data["subject"]
user = get_user_id(request)
id = user[0]['user_id']
c_ty=Company_Type(user_id=id,type=c_type)
c_ty.save(force_insert=True)
except:
print 'nope'
return JsonResponse({'status': 'success'})
Also if you need to make sure the id is an integer cast it to the right data type as int(id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.