Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting User object from username in django

I am trying the following code in a django celery task

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

My view is calling it as follows:

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

I am getting the following error:

>[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.

What I am trying to achieve is to pass the active user from the view into django-aync-messages

Any recommendations or pointers to my error (including a better way!) gratefully appreciated.

like image 571
arashiyama Avatar asked Jun 05 '14 12:06

arashiyama


2 Answers

There's nothing wrong with the way you're querying for the user. The problem with your code is that you have passed the variables in the wrong order: the task is expecting (q, userstring) but you are passing (username, query).

However I wonder why you are querying on username at all when you could simply pass the primary key of the User instance:

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

and call it:

search.delay(form.instance.query, self.request.user.pk)
like image 112
Daniel Roseman Avatar answered Sep 20 '22 02:09

Daniel Roseman


You need to handle the case when there is no user in some way for example:

@app.task
def search(q, userstring):
    try:
        uid = User.objects.get(username=userstring)
    except DoesNotExist, e:
        return None
like image 32
Rebecca Meritz Avatar answered Sep 20 '22 02:09

Rebecca Meritz