[英]Unable to get logged in username in django
I am trying to get User as foreignkey in a model but getting error.我试图在 model 中将用户作为外键,但出现错误。
qr.claimed = True
user = get_object_or_404(User,id=request.user.id)
qr.branch = user
qr.save();
OUTPUT: OUTPUT:
AttributeError: 'str' object has no attribute 'user'
qr.claimed = True
get_user = request.POST.get('branch')
user = User.objects.get(id=get_user)
qr.branch = user
qr.save();
OUTPUT: OUTPUT:
AttributeError: 'str' object has no attribute 'POST'
qr.claimed = True
get_user = pythonfile.user
user = User.objects.get(id=get_user)
qr.branch = user
qr.save();
OUTPUT: OUTPUT:
TypeError: Field 'id' expected a number but got <function user at 0x0E777E38>.
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.您传递给decode
的项目不是HttpRequest
object,而是 base64 编码的图像。 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']
request
而不是 。request.POST['imgBase64']
furthermore I would really advise not to make methods with a CSRF exeption.此外,我真的建议不要使用 CSRF 例外来制作方法。 You can send the CSRF token as specified in the AJAX section of the documentation .您可以按照文档的AJAX部分中的说明发送 CSRF 令牌。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.