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/", 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/", line 22, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/path/to/app/", 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/", 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 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):

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.