Unable to get logged in username in django - python

I am trying to get User as foreignkey in a model but getting error.
When I try:
qr.claimed = True
user = get_object_or_404(User,id=request.user.id)
qr.branch = user
qr.save();
OUTPUT:
AttributeError: 'str' object has no attribute 'user'
When I try to POST:
qr.claimed = True
get_user = request.POST.get('branch')
user = User.objects.get(id=get_user)
qr.branch = user
qr.save();
OUTPUT:
AttributeError: 'str' object has no attribute 'POST'
When I define user in another python file and try to fetch from there:
qr.claimed = True
get_user = pythonfile.user
user = User.objects.get(id=get_user)
qr.branch = user
qr.save();
OUTPUT:
TypeError: Field 'id' expected a number but got <function user at 0x0E777E38>.
request.user -> AttributeError: 'str' object has no attribute 'user'
request.POST -> AttributeError: 'str' object has no attribute 'POST'
Any error with request or missing any package to install/import?
UPDATE:
#csrf_exempt
def decodeAjax(request):
if request.POST:
decodedData = barCode.decode(request.POST['imgBase64'])
if decodedData:
json_data = json.dumps(decodedData)
print(json_data)
return JsonResponse(json_data,safe=False)
return JsonResponse({"code" : 'NO BarCode Found'})
def decode(request):
# Find barcodes and QR codes
imgstr = re.search(r'base64,(.*)', request).group(1) #url
image_bytes = io.BytesIO(base64.b64decode(imgstr))
im = Image.open(image_bytes)
arr = np.array(im)[:, :, 0]
decodedObjects = pyzbar.decode(arr)
#print(decodedObjects)
# return decodedObjects.Decoded
# Print results
data = []
for obj in decodedObjects:
qrs = Scanner.objects.all()
for qr in qrs:
if obj.data.decode('utf-8') in qr.ID:
dt = 'Successfully Claimed!'
btn = 'Claim Another'
img = 'tick.gif'
if qr.claimed == True:
dt = 'Already Claimed at %s'%(localtime(qr.scanned_at))
img = 'cross.png'
else:
qr.claimed = True
qr.save();
break
else:
dt = 'Invalid QR Code'
btn = 'Try Another'
img = 'cross.png'
data.append({
"code":obj.data.decode('utf-8') ,
#"type": obj.type,
"dt": dt,
"btn":btn,
"img":img
})
return data

You check the method with:
#csrf_exempt
def decodeAjax(request):
if request.method == 'POST':
decodedData = barCode.decode(request.POST['imgBase64'])
# …
The item you pass to decode is not a HttpRequest object, but the image in base64 encoding. You thus might want to rename this to:
def decode(base64img):
imgstr = re.search(r'base64,(.*)', base64img).group(1)
# …
If you need the request somewhere, you will need to pass request, not request.POST['imgBase64'].
furthermore I would really advise not to make methods with a CSRF exeption. You can send the CSRF token as specified in the AJAX section of the documentation.

Related

Why am I getting "Invalid salt" in django?

I have written a code for registration and login in django. While doing login, I am getting the error "Invalid salt"
Following is the code:
#api_view(['POST'])
def login(request):
email = request.data.get('email')
mobile_number = request.data.get('mobile_number')
pin = request.data.get('pin')
res = dict()
print(dict, "dictonaryyyyyy")
if email != None:
email_result = Users.objects.filter(email= email).first()
print(email_result.pin, "emaillll")
if email_result != None:
if bcrypt.checkpw(pin.encode("utf-8"), email_result.pin.encode('utf-8')):
# if bcrypt.checkpw(pin, )
print("........")
payload_data = dict()
payload_data['email'] = email_result.email
token = generate_token(payload_data)
print(token, "token.........")
res['messages'] = "Authentication Successful"
res['status'] = 200,
res['token'] = token
return Response(res, status = status.HTTP_200_OK)
...
...
How to get rid of this error?
It got solved, the hashed password was being saved as a binary instead of string at the time of registrattion.
To convert it into a string, the pin is required to be decoded at the time of creating the object.
pin = pin.decode('utf-8'),

how to convert httpresponse object to dictionary

first of all i'm sorry because of my duplicated question but actually the other didn't work for me at all.
my problem is that I have 2 views which the first one is returning a Httpresponse to the 2nd, and what I want is to convert this Httpresponse to dictionary in the 2nd view and have access to it's elements.
here is the code :
1st view:
def base_tag_upload(request, tag):
error = False
upload_msg = "success"
user = request.user
response_data = {"error": error, "upload_msg": upload_msg, "file_id": None, "file_version": None}
if request.method == 'POST':
form = UploadForm(request.POST or None, request.FILES or None, tag=tag, user=user)
if form.is_valid():
cd = form.cleaned_data
uploaded_file = cd['file']
collection_name = cd['new_name'] or uploaded_file.name.split('.')[0].strip()
response_data.update(
{"uf_name": uploaded_file.name, "uf_size": uploaded_file.size, "uf_colname": collection_name})
set_primary = True # first file in collection
# Finding/Creating Related FileCollection
collection = FileCollection.objects.create(name=collection_name)
is_major = cd['version_type'] == 'mj'
file_obj = collection.upload_file(uploaded_file, set_primary, Major_version=is_major)
file_obj.author = user
collection.tags.add(tag)
collection.get_tag_permissions(tag, False)
file_obj.get_collection_permissions(collection, False)
set_user_ownership(collection, tag, user)
set_user_ownership(file_obj, tag, user)
collection.save()
file_obj.collection = collection
file_obj.save()
response_data.update({'file_id':file_obj.id, 'file_version': file_obj.version})
ActionLog.log(action=Action.objects.get(name="create"), target=file_obj,
user=user, request=request, details=None, extra_details=None)
redirect_url = reverse('file_history', kwargs={'collection_id': collection.id})
response_data.update({'redirect': redirect_url})
return HttpResponse(json.dumps([response_data]))
and the 2nd one :
def tag_upload(request, tag_id):
try:
tag = Tag.objects.get(id=tag_id)
except Tag.DoesNotExist:
return HttpResponse(simplejson.dumps([{'error': 'value_error', 'upload_msg': "no such folder"}]))
k = base_tag_upload(request, tag)
k.response.decode('utf-8')
print k
return base_tag_upload(request, tag)
but I got this error when I wanted to decode the Httpresponse as shown above :
AttributeError: 'HttpResponse' object has no attribute 'response'
I have 2 views which the first one is returning a Httpresponse to the 2nd
Then you didn't structured your code properly - a view has no business calling another view not messing with the response.
If you need to share some common code between two views, then extract this code in a distinct function (that would in this case return a plain dict) and call this function from both your views.
It's k.content.decode('utf-8').

Strange error, Exception Value: type object has no attribute 'DoesNoExist'

I have this code. and i dont understand why it shows the error that i seem not to put the DoesNotExist handler when is already there.... and shows me this error:
AttributeError at /hotel/edit/hotel-riodssdfsdf-google-facebook-351/
type object 'hotel' has no attribute 'DoesNoExist'
Request Method: GET Request URL:
http::9000/hotel/edit/hotel-riodssdfsdf-google-facebook-351/ Django
Version: 1.6.2 Exception Type: AttributeError Exception Value:
type object 'hotel' has no attribute 'DoesNoExist'
Exception Location: views.py in update, line 171
LINE 171 is correct....: except hotel.DoesNoExist:
if 'member_id' not in request.session:
return HttpResponseRedirect('/login/')
else:
if request.POST:
try:
hotelObject = hotel.objects.get(slug=slug)
form = UpdateHotelForm(request.POST, instance=hotelObject)
if form.is_valid():
now = datetime.datetime.now()
name = form.cleaned_data['name']
slug_name = slugify(name + ' ' + str(now.microsecond))
hotels = hotel.objects.get(
id=hotelObject.id,
publisher=request.session['member_id'])
hotels.name = name
hotels.slug = slug_name
hotels.save()
args = {}
args.update(csrf(request))
args['form'] = form
args['message'] = False
args['name'] = hotelObject.name
return HttpResponseRedirect('/hotel/edit/' + slug_name)
else:
args = {}
args.update(csrf(request))
args['form'] = form
args['message'] = True
args['name'] = hotelObject.name
return render_to_response('hotel/edit_hotel.html', args)
except hotel.DoesNoExist:
return HttpResponseRedirect('/hotel/')
else:
try:
hotelObject = hotel.objects.get(slug=slug)
form = UpdateHotelForm(request.POST, instance=hotelObject)
form = UpdateHotelForm(instance=hotelObject)
args = {}
args.update(csrf(request))
args['form'] = form
args['name'] = hotelObject.name
return render_to_response('hotel/edit_hotel.html', args)
except hotel.DoesNoExist:
return HttpResponseRedirect('/hotel/')
The correct is hotel.DoesNotExist not hotel.DoesNoExiste a
You misspelled DoesNotExist as DoesNoExist. Change it to:
except hotel.DoesNotExist:

'str' object has no attribute 'csrf_exempt' while returning response from a django view?

I have this strange problem with my view which is returning response in json format.My view looks like this:
def CheckPlayer(request,client_id):
if request.method == 'GET':
try:
user = User.objects.get(id = client_id)
except:
return Error(message = "User doesnot exists.")
message = request.GET.get('message','')
if not message:
return Error(message = "Argument Missing.")
response = {}
result = MakingRequest(message)
result = json.loads(result)
if result['failure'] == '0':
response['failure'] = '0'
else:
response['failure'] = '1'
return HttpResponse(json.dumps(response), mimetype="application/javascript")
else:
return Error()
def MakingRequest(message):
values = {'message':message}
rObjects = Ram.objects.all()
temp = []
for i in rObjects:
temp.append(i.appId)
values['registration_ids'] = temp
param = json.dumps(values)
req = urllib2.Request("https://android.googleapis.com/gcm/send", param)
req.add_header( 'Content-Type' , 'application/json' )
req.add_header( 'Authorization' , 'key=7FcEMnl0FRTSBjhfjfhjfHi1Rmg04Ns' )
response = urllib2.urlopen(req)
return response.read()
I have tested it on my local server it works perfectly , but if I run it on my server (nginx,gunicorn,django-mongoDB,mongoDB) then it gives me this Error.I know about this error that if a view doesnot return HttpResponse from a view then it djangi raises error "Nonetype object has no attribute csrf_exempt' " but in my case i am returning response which is in json format but still its giving me error.Please help me
You aren't returning an HttpResponse when you return Error(), so Django can't apply the decorator to it.

django testing response.context TypeError: 'NoneType' object is not subscriptable

I want to test this view:
def register(request):
"""
handle user registration
code variable is for testing purposes
"""
if request.method== 'GET':
form = RegisterForm(auto_id=False)
code = 1
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
elif request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
password = form.cleaned_data['password']
password_confirmation = form.cleaned_data['password_confirmation']
if password == password_confirmation:
#if True:
login = form.cleaned_data['login']
email = form.cleaned_data['email']
newsletter = form.cleaned_data['newsletter']
key = register_user(login,email,password,newsletter)
if key:
#send email
send_mail("Dziękujemy za rejestrację"," Klucz aktywacyjny to " + key,settings.EMAIL_HOST_USER,[email])
request.session['email'] = email
return redirect(register_success)
else:
code = 4
error = "Login /email are taken"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 3
error = "invalid password"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 2
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
And here is my part of my test:
def test_valid_credentials(self):
#now try to register valid user
data = {'login':'test','password':'zaq12wsx','password_confirmation':'zaq12wsx','terms':True,'newsletter':True,'email':'test#test.com'}
response = self.c.post(reverse('register'),data)
#our user should be registred
self.assertEquals(302, response.status_code,'We dont have benn redirected')
self.assertEqual(len(mail.outbox), 1,'No activation email was sent')
#clen email box
mail.outbox = []
#now try to add anotheer user with the same data
response = self.c.post(reverse('register'),data)
#template should be rendered with error message about used login and email
self.assertEqual(response.context['code'],4)
And here is the error that I got:
,
in test_valid_credentials
self.assertEqual(response.context['code'],4)
TypeError: 'NoneType' object is not subscriptable
I tried it with get method and it works perfectly. Just with post it don't want to work.What am I doing wrong?Best regards
What is the response status? Redirects doesn't have context. Anyway, printing the response should help.
My guess is
key = register_user(login,email,password,newsletter)
throws an exception on duplicate register attempts and thus the handler does not generate a response.

Categories