Wednesday, August 19, 2015

Django - object has no attribute 'user' error

I got this error this morning when trying to test my Django app:

Internal Server Error: /staff/acts/email/
Traceback (most recent call last):
  File "/path/to/virtualenv/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/path/to/virtualenv/myenv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/path/to/app/views.py", line 519, in email_main
    confirm_sent = send_email(confirm_email_form, 'confirm', request)
  File "/path/to/virtualenv/myenv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    if test_func(request.user):
AttributeError: 'EmailTemplateForm' object has no attribute 'user'

I figured out the reason causing this issue is that I put the send_email function in views.py with a credential check decorator user_passes_test (which takes a required argument: a callable that takes a User object and returns True if the user is allowed to view the page, click here for more details):

@user_passes_test(user_is_staff,login_url="/")
def send_email(email_form, email_type, request):
...

But, my intention is to just use send_email as an utility function, so I just need to remove the decorator and everythin will be ok.


References:
[0] https://docs.djangoproject.com/en/1.5/topics/auth/default/#django.contrib.auth.decorators.user_passes_test
[1] http://stackoverflow.com/questions/14829788/function-object-has-no-attribute-user-error-in-django