我正在获取用户ID,并且我需要INT格式的ID,但只能通过函数return来获取。如何从函数转换为INT?我正在使用Django 2.1.7和python 3.7。
from django.contrib.auth import authenticate
from django.http import HttpRequest
request=HttpRequest
username='myuser'
password='mypass'
user = authenticate(username=username, password=password)
def user_id(request):
UID = request.user
return(UID)
UID=user_id
print(type(UID))
<class 'function'>
print(UID)
<function user_id at 0x106cd9158>
print(user.id)
19
views.py:
def get_userid(request):
if User.is_authenticated:
UID = request.user.id
return (UID)
if User.is_anonymous:
UID = 14
return (UID)
def opsearch(request):
item = request.POST['item']
dic = MLRun(item)
return render(request, 'main/layout/results.html', {'dictionary': dic})
我的调用模板的代码:
def to_DB(item, dic):
UID = get_userid
date_started = (timezone.now())
item_searched = item
Q = OPQuery(date_started=date_started,
item_searched=item_searched, id_user=UID)
Q.save()
QID = Q.id
QUID = OPQuery.objects.get(id=QID)
错误:
TypeError at /main/search/
int() argument must be a string, a bytes-like object or a number, not 'function'
Request Method: POST
Request URL: http://127.0.0.1:8000/main/search/
Django Version: 2.1.7
Exception Type: TypeError
Exception Value:
int() argument must be a string, a bytes-like object or a number, not 'function'
Exception Location: /usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 1807
Python Executable: /Users/Documents/PycharmProjects/OP/bin/python
Python Version: 3.7.2
答案 0 :(得分:0)
这段代码确实充满了问题。这里有一些。
在to_DB
中:
get_userid
函数,而只是引用了它。这是您立即错误的原因。在Python中,您始终需要使用()
来调用函数。request
参数传递给该函数。dic
参数。在get_userid
中:
is_authenticated
。应该是request.user.is_authenticated
。is_anonymous
类似。为了尽可能地具有建设性,您正在这里努力处理基本的Python概念。您确实需要返回并先做一个Python入门教程,然后再做Django教程。