Django's standard inclusion_tag doesn't include context variables by default.
When you add takes_context you are required to manually merge the context
variables into the dict which your tag returns, which tends to result in
wasteful code or [possibly accidentally] leaking variables into the global
context (`context.update({…})`).
This decorator allows your inclusion tag to remain simple and still have safe
access to the global context for things like `MEDIA_URL`:
@register.inclusion_tag('my_template')
@private_context
def my_tag(context, …):
return {"foo": 1, "bar": 2}
A simple context_processor to include location info. Useful for permalinks, site name references, and navigation bars. For example:
{% if location.path|match:"/$" %} class="current"{% endif %}
See also my [match filter](/snippets/1686/).
Simple middleware+decorator to handle age verification. Modeled after `django.contrib.sessions.middleware` to add an attribute to `request.user` called `is_age_verified` with consideration to [snippet 1002](http://www.djangosnippets.org/snippets/1002/). Decorator modeled after `django.contrib.auth.decorators.login_required`
Installation:
Create `verify_age` URLconf in `urls.py`
Create age verification page that URLconf points to
Define `settings.VERIFY_AGE_URL` based on URLconf
Add `age_verification.AgeVerificationMiddleware` to `MIDDLEWARE_CLASSES`
Import both `age_verification_required` and `REDIRECT_FIELD_NAME` in `views.py`
Implement `age_verification.AgeVerification.verify` somewhere to set session attribute on successful verification.
Use `@age_verification_required` decorator for views requiring age verification
Example urls.py:
urlpatterns += patterns('mahalo.answers.views',
...
url(r'^verify_age/?$', 'verify_age', name="verify_age"),
...
Example settings.py:
...
VERIFY_URL = '/verify_age/'
...
MIDDLEWARE_CLASSES += (
...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'myproject.contrib.middleware.age_verification.AgeVerificationMiddleware',
...
Example views.py:
from myproject.contrib.decorators import age_verification_required, REDIRECT_FIELD_NAME
from myproject.contrib.middleware.age_verification import AgeVerification
...
@age_verification_required
def some_view(request):
return render_to_response("index.html", {})
def verify_age(request):
# project specific
template_vars = default_template(request)
# form was posted
if request.POST.has_key("month") and request.POST.has_key("day") and \
request.POST.has_key("year"):
# "verify" user
av = AgeVerification(request.session)
av.verify()
if request.POST.has_key(REDIRECT_FIELD_NAME):
return HttpResponseRedirect(request.POST[REDIRECT_FIELD_NAME])
else:
return HttpResponseRedirect(reverse("root"))
# no form posted, show it
else:
if request.GET.has_key(REDIRECT_FIELD_NAME):
template_vars["next"] = request.GET[REDIRECT_FIELD_NAME]
return render_to_response("verify_age.html", template_vars)
These examples assume `age_verification.py` lives in `myproject/contrib/middleware/` and `decorators.py` lives in `myproject/contrib/`
Requires the M2Crypto module. See [http://sandbox.rulemaker.net/ngps/m2/howto.smime.html](http://sandbox.rulemaker.net/ngps/m2/howto.smime.html) for more information on using M2Crypto to create S/MIME email. This could also be adapted to allow signing, or sign+encrypt, but currently only encrypts.
Use just like `EmailMessage`, except takes an extra parameter `cert`, which is the path to the recipient's public X.509 certificate.
I wanted to be able to limit which types of requests a view will accept. For instance, if a view only wants to deal with GET requests.
@methods(GET)
def index(request):
# do stuff
Now, calling this view with a non-GET request will cause a 403.
You can easily change this to a 404, by using a different return function: which you may wish to do with openly available sites, as a 403 indicates there is a resource present.
Custom serialization, the poor try to make something like [django full serializers](http://code.google.com/p/wadofstuff/wiki/DjangoFullSerializers)
Usage:
you need two files, goodjson.py and goodpython.py, for example, in the root of application named "core". Then, add two lines into your settings.py:
SERIALIZATION_MODULES = {'goodjson' : 'core.goodjson',
'goodpython': 'core.goodpython'}
This thing does only serialization, not deserialization. You were warned.
Put this into the __init.py__ file in the root of your project (the same directory level as urls.py and settings.py) and this installs _() as a global reference into the current running python VM, and now it’s as universally available as int(), map(), or str().
This is, of course, controversial. Modifying the python global namespace to add a function can be considered maintenance-hostile. But the gettext feature is so universal– at least to me– that __init__.py is where it belongs.
This code overrides the existing RegistrationForm in django-registration and adds a new validation step. In this step, the username (my example slug) is compared against all the existing URLs that the application currently resolves and, if it *does* successfully resolve, throws a validation exception. This indicates that the username chosen would be overriden (or, if you wrote your urls.py file badly, would override) an existing URL already recognized by your application.
A much longer explanation can be found at [Dynamic names as first-level URL path objects in Django](http://www.elfsternberg.com/2009/06/26/dynamic-names-as-first-level-url-path-objects-in-django/).
A filter that changes a preparsed date from [Ultimate Feedparser](http://www.feedparser.org/) to a regular datetime instance.
Now you can -for example- pass a feed parsed by feedparser to a template and do this:
{% for item in feed.entries %}
Title: {{ item.title }}<br />
Date: {{ item.updated_parsed|feedparsed|date:"Y-m-d" }}
{% endfor %}
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.