how to activate DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST - django

I read this
DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST
If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every
RequestContext will contain a variable request, which is the current
HttpRequest. Note that this processor is not enabled by default;
you'll have to activate it.
from this page
But it seems there is no information how to activate this processor.
Here is my original question
Access request in django custom template tags
After i followed the answer
i still got errors
TemplateSyntaxError at / Caught an exception while rendering: 'request' Original Traceback (most recent call last):
File "C:\Python25\lib\site-packages\django\template\debug.py", line 71, in render_node result = node.render(context)
File "C:\Python25\lib\site-packages\django\template__init__.py", line 936, in render dict = func(*args)
File "c:\...\myapp_extras.py", line 7, in login request = context['request']
File "C:\Python25\lib\site-packages\django\template\context.py", line 44, in getitem raise KeyError(key) KeyError: 'request'
the code causing problem is
request = context['request'] in
from django import template
register = template.Library()
#register.inclusion_tag('userinfo.html',takes_context = True)
def userinfo(context):
request = context['request']
address = request.session['address']
return {'address':address}

I answered this here: How can I pass data to any template from any view in Django?
Also see the comments on my answer... you might want that bit of info too.

in settings.py
from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'django.core.context_processors.request',
)

Related

Log warning from Selenium on Django [duplicate]

Whenever I try to construct a string based on self.live_server_url, I get python TypeError messages. For example, I've tried the following string constructions (form 1 & 2 below), but I experience the same TypeError. My desired string is the Live Server URL with "/lists" appended. NOTE: the actual test does succeed to create a server and I can manually access the server, and more specifically, I can manually access the exact URL that I'm trying to build programmatically (e.g. 'http://localhost:8081/lists').
TypeErrors occur with these string constructions.
# FORM 1
lists_live_server_url = '%s%s' % (self.live_server_url, '/lists')
# FORM 2
lists_live_server_url = '{0}{1}'.format(self.live_server_url, '/lists')
self.browser.get(lists_live_server_url)
There is no python error with this form (nothing appended to string), albeit my test fails (as I would expect since it isn't accessing /lists).
self.browser.get(self.live_server_url)
Here is the python error that I'm getting.
/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Applications/PyCharm.app/Contents/helpers/pycharm/django_test_manage.py test functional_tests.lists_tests.LiveNewVisitorTest.test_can_start_a_list_and_retrieve_it_later /Users/myusername/PycharmProjects/mysite_proj
Testing started at 11:55 AM ...
Creating test database for alias 'default'...
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/wsgiref/handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python3.4/site-packages/django/test/testcases.py", line 1104, in __call__
return super(FSFilesHandler, self).__call__(environ, start_response)
File "/usr/local/lib/python3.4/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
response = self.get_response(request)
File "/usr/local/lib/python3.4/site-packages/django/test/testcases.py", line 1087, in get_response
return self.serve(request)
File "/usr/local/lib/python3.4/site-packages/django/test/testcases.py", line 1099, in serve
return serve(request, final_rel_path, document_root=self.get_base_dir())
File "/usr/local/lib/python3.4/site-packages/django/views/static.py", line 54, in serve
fullpath = os.path.join(document_root, newpath)
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/posixpath.py", line 82, in join
path += b
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'
Am I unknowingly attempting to modify the live_server_url, which is leading to these TypeErrors? How could I programmatically build a string of live_server_url + "/lists"?
Here is the test that I am attempting...
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
class LiveNewVisitorTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Chrome()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.close()
def test_can_start_a_list_and_retrieve_it_later(self):
#self.browser.get('http://localhost:8000/lists')
#self.browser.get('http://www.google.com')
#lists_live_server_url = '%s%s' % (self.live_server_url, '/lists')
#lists_live_server_url = '{0}{1}'.format(self.live_server_url, '/lists')
lists_live_server_url = self.live_server_url
self.browser.get(lists_live_server_url)
self.assertIn('To-Do', self.browser.title)
header_text = self.browser.find_element_by_tag_name('h1').text
self.assertIn('To-Do', header_text)
See this discussion on Reddit featuring the same error Traceback.
Basically, this is not a problem with anything within the Selenium tests but rather with your project's static file configuration.
From your question, I believe the key line within the Traceback is:
File "/usr/local/lib/python3.4/site-packages/django/views/static.py", line 54, in serve
fullpath = os.path.join(document_root, newpath)
This line indicates that an unsuccessful os.path.join is being attempted within django.views.static.
Set STATIC_ROOT in your project's settings.pyfile and you should be good.
Use StaticLiveServerTestCase instead may help

How to cache a view method without a route?

I'm trying to test caching in my code. I am using memcached as the backend. I set the CACHE config to use memcached under 'basic'. There isn't a direct route to the get_stuff method. Here is my code:
I have a view that looks like
from .models import MyModel
from django.views.decorators.cache import cache_page
class MyView(TemplateView):
""" Django view ... """
template_name = "home.html"
#cache_page(60 * 15, cache="basic")
def get_stuff(self): # pylint: disable=no-self-use
""" Get all ... """
return MyModel.objects.filter(visible=True, type=MyModel.CONSTANT)
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
stuffs = self.get_stuff()
if stuffs:
context['stuff'] = random.choice(stuffs)
return context
I also have a test that looks like
from django.test.client import RequestFactory
from xyz.apps.appname import views
class MyViewTestCase(TestCase):
""" Unit tests for the MyView class """
def test_caching_get_stuff(self):
""" Tests that we are properly caching the query to get all stuffs """
view = views.MyView.as_view()
factory = RequestFactory()
request = factory.get('/')
response = view(request)
print response.context_data['stuff']
When I run my test I get this error:
Traceback (most recent call last):
File "/path/to/app/appname/tests.py", line 142, in test_caching_get_stuff
response = view(request)
File "/usr/local/lib/python2.7/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/views/generic/base.py", line 87, in dispatch
return handler(request, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/views/generic/base.py", line 154, in get
context = self.get_context_data(**kwargs)
File "/path/to/app/appname/views.py", line 50, in get_context_data
stuffs = self.get_stuff()
File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 91, in _wrapped_view
result = middleware.process_request(request)
File "/usr/local/lib/python2.7/site-packages/django/middleware/cache.py", line 134, in process_request
if not request.method in ('GET', 'HEAD'):
AttributeError: 'MyView' object has no attribute 'method'
What is causing this and how do I fix this? I'm fairly new to Python and Django.
Can you show the what you have for MIDDLEWARE_CLASSES in settings.py? I looked through the code where your error showed up, and it notes that FetchFromCacheMiddleware must be last piece of middleware in the MIDDLEWARE_CLASSES. I wonder if that is causing your problem.
Related documentation here.
I believe the issue is that the cache_page decorator is meant to be used on view functions, not to decorate methods of class-based views. View functions take 'request' as their first argument, and if you look at the traceback, you can see that in fact the error is caused because the first argument of the function you tried to decorate is not a request but rather 'self' (i.e., the MyView object referred to in the error).
I am not sure if or how the cache_page decorator can be used for class-based views, though this page in the docs suggests a way of using it in the URLconf and I imagine you could wrap the return of ViewClass.as_view in a similar fashion. If the thing you're trying to wrap in caching is not properly a view but rather a utility function of some sort, you should drop to using the more manual lower-level cache API inside of your function (not as a decorator).

AttributeError: 'WSGIRequest' object has no attribute 'request' on OAuth2Decorator

I ran into an issue using Django on Google App Engine trying to access Google API.
I want to use the decorator, as described in the docs, but I get the same error over and over again:
AttributeError: 'WSGIRequest' object has no attribute 'request'
And the StackTrace:
Internal Server Error: /
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/Users/johannes/GitHub/itzehoe/dependencies/oauth2client/appengine.py", line 703, in check_oauth
self._create_flow(request_handler)
File "/Users/johannes/GitHub/itzehoe/dependencies/oauth2client/appengine.py", line 734, in _create_flow
redirect_uri = request_handler.request.relative_url(
AttributeError: 'WSGIRequest' object has no attribute 'request'
And some code:
from google.appengine.api import users
from oauth2client.appengine import OAuth2DecoratorFromClientSecrets
from django.shortcuts import render
from django.conf import settings
decorator = OAuth2DecoratorFromClientSecrets(settings.GOOGLE_CLIENT_SECRETS,
'https://www.googleapis.com/auth/admin.directory.group')
#decorator.oauth_required
def index(request):
context = {}
return render(request, 'index.html', context)
The OAuth2Decorator functionality assumes you're wrapping methods in a webapp or webapp2 RequestHandler subclass, it's not designed to work with django views.

django custom templatetag not getting request in context

I am using django 1.4 and trying to convert the code described at the end of this article into a customtag. This means I need access to the is_secure and site_name values from the request. Here is my CONTEXT_PROCESSORS in settings.py:
CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
)
Here is my template tag code:
from django import template
register = template.Library()
#register.simple_tag(takes_context=True)
def full_static_url(context, url):
request = context['request']
scheme = 'http'
if request.is_secure:
scheme += 's'
return scheme + '://' + request.site_name + context['STATIC_URL'] + url
In my view code I am using the new render shortcut like so:
return render(request, 'myapp/mytemplate.html', {'foo':bar})
And I am calling it like this in the template:
{% full_static_url "images/logo.gif" %}
The problem is, when it gets to the line request = context['request'] it throws a KeyError because 'request' is not in context.
What am I doing wrong here?
Full traceback is:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Projects\blah\blah\myapp\views\myview.py" in manifestcosts
44. return render(request, 'myapp/mytemplate.html', {'foo':bar})
File "C:\Python27\lib\site-packages\django\shortcuts\__init__.py" in render
44. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
176. return t.render(context_instance)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
140. return self._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
823. bit = self.render_node(node, context)
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
74. return node.render(context)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
185. nodelist.append(node.render(context))
File "C:\Python27\lib\site-packages\django\template\base.py" in render
1107. return func(*resolved_args, **resolved_kwargs)
File "C:\Projects\blah\blah\myapp\templatetags\mytags.py" in full_static_url
25. request = context['request'] #TODO this fails with an KeyError, don't know why
File "C:\Python27\lib\site-packages\django\template\context.py" in __getitem__
54. raise KeyError(key)
Exception Type: KeyError at /myapp/myurl/110505081136179000/
Exception Value: 'request'
The right way to fix this issue is to add TEMPLATE_CONTEXT_PROCESSORS += ("django.core.context_processors.request",) on your settings.py file.
Ensure to import TEMPLATE_CONTEXT_PROCESSORS first with from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS or it will not work.
Most likely the problem is you are rendering your template using regular context, that is something like this:
return render_to_response("myapp/template.html", {"some_var": a_value})
Remember that context processors are only applied to RequestContext instances. That means you have to either explicitly create a RequestContext in your render_to_response call:
return render_to_response("myapp/template.html", {"some_var": a_value},
context_instance=RequestContext(request))
or even better, use the new render shortcut:
return render(request, "myapp/template.html", {"some_var": a_value})
I solved it by changing
return render(request, 'myapp/mytemplate.html', {'foo':bar})
to
return render( RequestContext(request), 'myapp/mytemplate.html', {'foo':bar})
I hope this helps someone else, I wasted about 8 hours :p
I had this happen in a template.Node object in the render(). It turned out that sometimes the context had 'request' in it, other times it didn't.
Like someone else suggested, RequestContext(request) is the key. My guess is that sometimes the context is called without the request being initialized like that.
I changed my function from
def render(self, context):
request = context['request'] # Failing here
to
def render(self, context):
request = RequestContext(context)['request']['request']
and it all came right.
This will force a request object in case the context object wasn't initialized properly. For some reason I had to add ['request'] twice, but it seems to work fine
EDIT: I spoke too soon, seems a blank context can't be fixed. Instead you could try a workaround:
request = context.get('request')
if request is None:
return ''
My page still seems to work fine, so I'm not exactly sure where these bad contexts are coming from.

Django preview, TypeError: 'str' object is not callable

I'm trying to make a Preview function. I'm reading this blog, Django Admin Preview, but now I have the following error and I don't know what it means.
Traceback (most recent call last):
File "/home/user/webapps/django/lib/python2.5/django/core/handlers/base.py", line 92, in get_response
response = callback(request, *callback_args, **callback_kwargs)
TypeError: 'str' object is not callable
I'm lost..
Edit:
Thanks guys/gals, here is my view.py and url.py:
from diligencia.diligencias.views import preview
url(r'^admin/diligencias/diligencia/(?P<object_id>\d+)/preview/$','preview'),
(r'^admin/(.*)', admin.site.root),
from diligencia.diligencias.models import Diligencia
#staff_member_required
def preview(request, object_id):
return object_detail(request, object_id=object_id,queryset=Diligencia.objects.all(), template_object_name = 'diligencia_detail.html', )
The signature for the url function within a urlconf is like this:
def url(regex, view, kwargs=None, name=None, prefix='')
You are using positional parameters only, but are passing only regex, view and name. So Python thinks your third parameter is the kwargs dictionary, not the name.
Instead, do this:
url(r'^admin/diligencias/diligencia/(?P<object_id>\d+)/preview/$', name='preview'),
to pass the name as a kwarg so that Python recognises it properly.
I suspect your view isn't a function. Make sure the argument in your urls.py is a function that takes one parameter. Like :
import default
url(r'^s(?:ite)?/search$', default.search, name="search"),
And then you have in default.py
def search(request) :
# do stuff