从django中的用户名获取User对象

时间:2014-06-05 12:19:58

标签: python django python-2.7 celery

我在django芹菜任务中尝试以下代码

@app.task
def search(q, userstring):
    uid = User.objects.get(username=userstring)
    messages.info(uid, 'Initiating search in background.')
    [...]

我的观点如下:

search.delay(self.request.user.get_username(), form.instance.query)

我收到以下错误:

>[2014-06-05 12:04:04,352: ERROR/MainProcess] Task listthings.tasks.search[5aaa77b4-c7be-4d6a-9127-626e63d0dfbe] raised unexpected: DoesNotExist('User matching query does not >exist.',)
Traceback (most recent call last):
  File "/webapps/wcw/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/webapps/wcw/local/lib/python2.7/site-packages/celery/app/trace.py", line 437, in __protected_call__
    return self.run(*args, **kwargs)
  __File "/webapps/wcw/webcamwatch/listcams/tasks.py", line 44, in search
    uid = User.objects.get(username=userstring)__
  File "/webapps/wcw/local/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get
    return self.get_queryset().get(*args, **kwargs)
  File "/webapps/wcw/local/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get
    self.model._meta.object_name)
Exception: User matching query does not exist.

我想要实现的是将活动用户从视图传递到django-aync-messages

我的错误的任何建议或指针(包括更好的方式!)非常感谢。

2 个答案:

答案 0 :(得分:3)

您查询用户的方式没有任何问题。您的代码的问题在于您以错误的顺序传递了变量:任务期待(q, userstring),但您正在传递(username, query)

但是我想知道为什么你只需要传递User实例的主键就可以查询用户名:

def search(q, user_id):
    uid = User.objects.get(pk=user_id)

并称之为:

search.delay(form.instance.query, self.request.user.pk)

答案 1 :(得分:0)

例如,当某个用户没有用户时,你需要处理这个案例:

@app.task
def search(q, userstring):
    try:
        uid = User.objects.get(username=userstring)
    except DoesNotExist, e:
        return None