简体   繁体   中英

Django Context Processor Login In Issue

I have a login system:

def login(request):
title = "Login"
if request.user.is_authenticated():
    return HttpResponseRedirect('/')
form = UserLoginForm(request.POST or None)
if request.POST and form.is_valid():
    username = form.cleaned_data.get('username')
    password = form.cleaned_data.get('password')
    user = auth.authenticate(username=username, password=password)
    if user:
        auth.login(request, user)
    return HttpResponseRedirect("/")# Redirect to a success page.
return render(request, 'accounts/login.html', {'title':title, 'form': form })


def logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/accounts/login')

and it works fine. However, when I try to add in a context_processor it stops working and gives me the following error:

Environment:


Request Method: GET
Request URL: http://localhost:8000/accounts/login/

Traceback:

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/Users/andyxu/Documents/ece496-web/capstone/views.py" in login
  22.     return render(request, 'accounts/login.html', {'title':title, 'form': form })

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  68.     return template.render(context, request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  206.                 with context.bind_template(self):

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__
  17.             return self.gen.next()

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/context.py" in bind_template
  236.             updates.update(processor(self.request))

Exception Type: TypeError at /accounts/login/
Exception Value: 'NoneType' object is not iterable

Here is my context_processor.py:

from matchalgorithm.models import Profile

def add_variable_to_context(request):
    if(request.user.id):
        profile = Profile.objects.filter(user_id = request.user.id).first()
    return {
        'main_profile': profile
    }

Basically I just want to check if the user has a Profile else return None . I want to use this variable to be passed into my base.html which is NOT rendered by any view. Funny thing is, once I am logged in , it works fine!

Thanks

The indentation on your context processor seems to be off, it doesn't match your description. I assume that the return statement is inside the if statement, since it matches both your description and the traceback.

The docs say (emphasis mine):

A context processor has a very simple interface: It's a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

So if you don't want to add anything to the context, your processor must return an empty dictionary instead of None :

def add_variable_to_context(request):
    if(request.user.id):
        profile = Profile.objects.filter(user_id = request.user.id).first()
        return {
            'main_profile': profile
        }
    return {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM