Some cache problems - django

I'm wondering if I can delete a cached content made in template cache. I want to delete it from my view. I have in my template {% cache 500 cache_name sites.number %}
Is it possible to delete all "cache_name" cached content within the view, for example when some action is made?
I want to use per-vie cache. I do all what is described, but when I call: #cache_page(3600, cache="cache_name") I get error:
Exception Type: ValueError Exception
Value: need more than 1 value to
unpack
(Below is the traceback)
What I want to achieve is to cache all my template block or view and have a possibility to delete all cache connected with it when some actions are made. Pagination is included
Traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/portfolio/
Django Version: 1.3 beta 1 SVN-15661
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'apps.index']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "E:\Python\django\core\handlers\base.py" in get_response
101. request.path_info)
File "E:\Python\django\core\urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "E:\Python\django\core\urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "E:\Python\django\core\urlresolvers.py" in resolve
158. return ResolverMatch(self.callback, args, kwargs, self.name)
File "E:\Python\django\core\urlresolvers.py" in _get_callback
164. self._callback = get_callable(self._callback_str)
File "E:\Python\django\utils\functional.py" in wrapper
124. result = func(*args)
File "E:\Python\django\core\urlresolvers.py" in get_callable
91. lookup_view = getattr(import_module(mod_name), func_name)
File "E:\Python\django\utils\importlib.py" in import_module
35. __import__(name)
File "E:\Python\apps\index\views.py" in <module>
29. #cache_page(600, cache='my_cache')
File "E:\Python\django\views\decorators\cache.py" in cache_page
58. return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
File "E:\Python\django\utils\decorators.py" in _make_decorator
81. middleware = middleware_class(*m_args, **m_kwargs)
File "E:\Python\django\middleware\cache.py" in __init__
204. self.cache = get_cache(self.cache_alias, **cache_kwargs)
File "E:\Python\django\core\cache\__init__.py" in get_cache
173. backend, location, params = parse_backend_conf(backend, **kwargs)
File "E:\Python\django\core\cache\__init__.py" in parse_backend_conf
131. mod_path, cls_name = backend.rsplit('.', 1)
Exception Type: ValueError at /portfolio/
Exception Value: need more than 1 value to unpack

What version of Django are you using? The parameter "cache" is only available in the development version. If you're using Django 1.2, you can only use "key_prefix".

http://docs.djangoproject.com/en/1.2/topics/cache/
The cache middleware caches every page
that doesn't have GET or POST
parameters.

Related

Django says OverflowError at /admin/ while trying to access /admin/

I noticed this error while trying to access /admin/. Whenever /admin/model_name or /admin/ or /admin/* is accessed django says OverflowError at /admin/ and regular expression code size limit exceeded. I did a little digging and came across this SO post. I have checked urls.py of app since regex are mostly used in urls. But all I have is a typical admin url, nothing complex.
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
....
]
Stack trace
Environment:
Request Method: GET
Request URL: http://domain/admin/
Django Version: 1.9.8
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'haystack',
'myapp.apps.core',
'myapp.apps.home',
'myapp.apps.accounts',
'myapp.apps.dashboard',
'myapp.apps.app1',
'myapp.apps.app3',
'myapp.apps.app5',
'myapp.apps.app6',
'myapp.apps.app7',
'myapp.apps.app8',
'myapp.apps.app9']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in wrapper
265. return self.admin_view(view, cacheable)(*args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in index
505. app_list = self.get_app_list(request)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in get_app_list
488. app_dict = self._build_app_dict(request)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in _build_app_dict
473. current_app=self.name,
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._revers>e_with_prefix(view, prefix, *args, **kwargs)))
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix>
488. if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % candidate_subs, re.UNICODE):
File "/usr/lib/python2.7/re.py" in search>
142. return _compile(pattern, flags).search(string)
File "/usr/lib/python2.7/re.py" in _compile>
242. p = sre_compile.compile(pattern, flags)
File "/usr/lib/python2.7/sre_compile.py" in compile
521. groupindex, indexgroup
Exception Type: OverflowError at /admin/
Exception Value: regular expression code size limit exceeded
We are using django+apache.
Any help is much appreciated.
TIA
I have managed to solve this by restarting apache2 with
sudo service apache2 restart.
Of course, I have inspected apache2 error log with
sudo tail-f /var/logs/apache2/error.log
But that gave me same output as stack trace. Aforementioned is a work around for this issue. I am not marking this question as solved since real issue have not been found yet.
Thanks.

Django 1.9: 'AnonymousUser' object is not iterable

I was working on a Django 1.9 project, and suddenly this error popped up when I attempted to view my site's home page as a logged-out user.
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.9.7
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'captcha',
'debug_toolbar',
'django_extensions',
'djstripe',
'crm',
'launch',
'rentals',
'widget_tweaks']
Installed Middleware:
[u'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
172. response = response.render()
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in render
160. self.content = self.rendered_content
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in rendered_content
137. content = template.render(context, self._request)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/backends/django.py" in render
95. return self.template.render(context)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/base.py" in render
204. with context.bind_template(self):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__
17. return self.gen.next()
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/debug_toolbar/panels/templates/panel.py" in _request_context_bind_template
79. context = processor(self.request)
File "/Users/me/projects/rentalguru/src/rentals/processors.py" in allCategories
4. expense_categories = ExpenseCategory.objects.filter(user=request.user)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in filter
790. return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
808. clone.query.add_q(Q(*args, **kwargs))
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
1243. clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
1269. allow_joins=allow_joins, split_subq=split_subq,
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
1174. self.check_related_objects(field, value, opts)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in check_related_objects
1073. for v in value:
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/utils/functional.py" in inner
205. return func(self._wrapped, *args)
Exception Type: TypeError at /
Exception Value: 'AnonymousUser' object is not iterable
I'm not sure what would be causing this, and there's only one Google search result (for this site) for this error. I searched the code for the is_authenticated() method and didn't find anything, so I'm unsure where to turn. Working through the stack trace didn't show any useful (for me) information.
Here is my view:
class HomePageView(TemplateView):
template_name = 'home.html'
No login decorators or wrapped functions that I can tell.
Let me know if I need to post anything else.
EDIT: Asked for the model, here is the offending context processor instead:
def allCategories(request):
expense_categories = ExpenseCategory.objects.filter(user=request.user)
tags = {'categories': expense_categories}
return tags
I just stumbled myself upon this error. Thankfully the answer was provided in the comments:
As you said you tried to view home page with logged out user and this ExpenseCategory.objects.filter(user=request.user) filtering of Anonymous user (because you are logged out now) seems to be the culprit. Either you should allow only a authenticated user to this view or handle the case where your user is Anonymous
As for myself, I had a view, where I was filtering on a model based on the current user, which apparantly fails, when the user is the AnonymousUser.
I fixed this by adding a check:
if request.user.is_active:
expense_categories = ExpenseCategory.objects.filter(user=request.user)
Note that some people seem to prefer to check request.user.is_authenticated instead.
If you are dealing with a view that shall be accessed by logged in users only, you can also use the #login_required decorator.
For reference:
https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_active
https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated
https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.decorators.login_required

How generate a pdf file with django-wkhtmltopdf on IIS 7.5 - 8

I use django-wkhtmltopdf to generate pdfs in my webapp, Works fine using the django integrate server, but when I use IIS 7.5 or 8 gives me this error: WindowsError [Error 6] The handle is invalid
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8006/blabla/pdf/10/
Django Version: 1.8.5
Python Version: 2.7.10
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'NuevoTicket',
'crispy_forms',
'wkhtmltopdf',
'ckeditor',
'ckeditor_uploader')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
164. response = response.render()
File "C:\Python27\lib\site-packages\django\template\response.py" in render
158. self.content = self.rendered_content
File "C:\Python27\lib\site-packages\wkhtmltopdf\views.py" in rendered_content
78. cmd_options=cmd_options
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in render_pdf_from_template
159. cmd_options=cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in convert_to_pdf
121. return wkhtmltopdf(pages=[filename], **cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in wkhtmltopdf
109. return check_output(ck_args, **ck_kwargs)
File "C:\Python27\lib\subprocess.py" in check_output
566. process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "C:\Python27\lib\subprocess.py" in __init__
702. errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
File "C:\Python27\lib\subprocess.py" in _get_handles
857. errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Exception Type: WindowsError at /blabla/pdf/10/
Exception Value: 6 The handle is invalid
Finally got it, thank's to n1b0r. I have to update the check_out method in python27/lib/subprocess.py like this
from:
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
to:
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
kwargs.pop('stderr', None)
process = Popen(stdout=PIPE, stderr=PIPE, stdin=PIPE, *popenargs, **kwargs)
That make it works in IIS but gives an error if use the django integrate server.
I used to have the same problem. Add the option quiet to the pdfkit and also try to modify the file configuration.py from pdfkit
options = {'quiet': ''}
pdfkit.from_file('in.html', 'out.pdf',options = options)
configuration.py
from this:
self.wkhtmltopdf = subprocess.Popen(['where','wkhtmltopdf'],stdout=subprocess.PIPE).communicate()[0].strip()
to:
self.wkhtmltopdf = subprocess.Popen(['which','wkhtmltopdf'],stdin=subprocess.PIPE,stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0].strip()

Getting 403 Forbidden when using Oauth2.0

I am using "Oauth2.0" to access YouTube data API.
the site is hosted on a Django platform, its address is http://listplay1.pythonanywhere.com/
Every time I'd like to authorize myself I refresh the access token and use the new one to get access.
Most of the time it works flawlessly but sometimes I get 403 Forbidden error. when I do the same from the terminal on my pc it works always
Can anyone have an idea in regards to how is it happening only part of the time and more importantly, how to fix it?
Thanks a mill in advance,
*the $$$ parts are hidden on purpose of course.
def auth():
h={'Host':'accounts.google.com','Content-Type':'application/x-www-form-urlencoded','X-GData-Key':'key=$$$'}
content={'client_id':'567194806765-r1pdllkji4tpgv1dc0a9ihrvh0hocoik.apps.googleusercontent.com','client_secret':'$$$','refresh_token':'$$$','grant_type':'refresh_token'}
p=urllib.urlencode(content)
r = requests.post('https://accounts.google.com/o/oauth2/token', data=p,headers=h)
token=r.json().values()[0]
credentials = AccessTokenCredentials(token,'my-user-agent/1.0')
return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,http=credentials.authorize(httplib2.Http()))
and the error
Environment:
Request Method: GET
Request URL: http://listplay1.pythonanywhere.com/thanks/
Django Version: 1.3.7
Python Version: 2.7.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'main.myapp']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "./main/myapp/views.py" in thanks
64. Pid=create_playlist(YT="",title=TITLE)
File "/home/LISTPLAY1/LISTPLAY/listplay.py" in create_playlist
261. YT=auth()
File "/home/LISTPLAY1/LISTPLAY/listplay.py" in auth
257. return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,http=credentials.authorize(httplib2.Http()))
File "/home/LISTPLAY1/LISTPLAY/oauth2client/util.py" in positional_wrapper
132. return wrapped(*args, **kwargs)
File "/home/LISTPLAY1/LISTPLAY/apiclient/discovery.py" in build
192. resp, content = http.request(requested_url)
File "/home/LISTPLAY1/LISTPLAY/oauth2client/util.py" in positional_wrapper
132. return wrapped(*args, **kwargs)
File "/home/LISTPLAY1/LISTPLAY/oauth2client/client.py" in new_request
490. redirections, connection_type)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py" in request
1570. (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py" in _request
1317. (response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py" in _conn_request
1252. conn.connect()
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py" in connect
1018. sock.connect((self.host, self.port))
File "/usr/local/lib/python2.7/dist-packages/httplib2/socks.py" in connect
424. self.__negotiatehttp(destpair[0], destpair[1])
File "/usr/local/lib/python2.7/dist-packages/httplib2/socks.py" in __negotiatehttp
390. raise HTTPError((statuscode, statusline[2]))
Exception Type: HTTPError at /thanks/
Exception Value: (403, 'Forbidden')

ViewDoesNotExist at /accounts/register/ (django-registration-me error)

I am currently working on a project which uses mongoengine and django. I am using django-registration-me to handle user registrations, but I am having problems after submitting the new user registration form.
The error I am receiving is:
"ViewDoesNotExist at /accounts/register/" "Tried settings in module
core.views. Error was: 'module' object has no attribute 'settings'"
It sends a verification email out fine though. I am new to django and mongoengine, so any help with this would be greatly appreciated.
The traceback is below.
Environment:
Request Method: POST Request URL:
http://dev.teamfit.us:8000/accounts/register/
Django Version: 1.3 beta 1 SVN-15207
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'registration']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File
"/usr/src/django-trunk/django/core/handlers/base.py"
in get_response
111. response = callback(request,
*callback_args, **callback_kwargs)
File
"/usr/local/lib/python2.6/dist-packages/django_registration_me-0.7-py2.6.egg/registration/views.py"
in register
153. return HttpResponseRedirect(success_url or
reverse('registration_complete'))
File
"/usr/src/django-trunk/django/core/urlresolvers.py"
in reverse
390. *args, **kwargs)))
File
"/usr/src/django-trunk/django/core/urlresolvers.py"
in reverse
311. possibilities = self.reverse_dict.getlist(lookup_view)
File
"/usr/src/django-trunk/django/core/urlresolvers.py"
in _get_reverse_dict
228. self._populate()
File
"/usr/src/django-trunk/django/core/urlresolvers.py"
in _populate
219. lookups.appendlist(pattern.callback,
(bits, p_pattern))
File
"/usr/src/django-trunk/django/core/urlresolvers.py"
in _get_callback
169. raise ViewDoesNotExist("Tried %s in module
%s. Error was: %s" % (func_name,
mod_name, str(e)))
Exception Type: ViewDoesNotExist at
/accounts/register/
Exception Value: Tried settings in
module core.views. Error was: 'module'
object has no attribute 'settings'
I guess, you have
import settings
or some such variation in your code.
You should change it to:
from django.conf import settings
and it should work