简体   繁体   中英

Variable in Django Context Processor

I want to register a variable in a context processor but the problem that occurs is that it didn't work and doesn't display any error.

views.py :-

def newmessage(request):
    getmessagevalue = interview.objects.all()
    return {'getmessagevalue': getmessagevalue }

settings.py :-

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.static",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
    "django.core.context_processors.tz",
    "userprofile.views.newmessage"

)

What can I do, the error and value is not displayed.

The code you've shown us looks ok to me. You need to make sure that your view (which you haven't shown) is rendering the template using a request context. See the docs for more information.

Add logging or print statements to your context processor to make sure it is running in your view. Perhaps there are no interview objects in your database, so it's returning an empty queryset.

Another option to aid debugging is to install the Django debug toolbar . It has a Template panel which shows you the output of your template context processors.

Another couple of suggestions:

  • name your model Interview , and use underscores for your method new_message and variable get_message_value names.
  • put your context processor in a separate module userprofile.context_processors instead of in your views module.

If you follow these conventions, your code is much easier for experienced python and Django developers to read, so you're more likely to get answers to your questions.

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