Login

All snippets written in Python

2956 snippets

Snippet List

Cookieless Session Decorator

Although many people have already posted cookieless session middlewares and related stuffs, but this one is just for only required views. You can use this as a view decorator like: @session_from_http_params @login_required def your_view(request): ... This is very useful for those who use SWFUpload. Flash has a bug with sending cookies properly, so SWFUpload offers an workaround -- session key as a POST parameter.

  • session
  • decorator
  • cookieless
Read More

Simple Age Verification Middleware

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/`

  • middleware
  • session
  • age-verification
  • session-backed
Read More

Sanitize HTML filter with tag/attribute whitelist and XSS protection

Reworked version of [this snippet](http://www.djangosnippets.org/snippets/205/) that now accepts an argument so the user can specify which tags to allow, and which attributes should be allowed for each tag. Argument should be in form `tag2:attr1:attr2 tag2:attr1 tag3`, where tags are allowed HTML tags, and attrs are the allowed attributes for that tag. It also uses code from [this post on stack overflow](http://stackoverflow.com/questions/16861/sanitising-user-input-using-python) to add XSS protection.

  • html
  • security
  • sanitize
  • whitelist
Read More

Template tags to integrate with modconcat

Assumes mod_concat is installed: http://code.google.com/p/modconcat/ Django template tags that combine blocks of CSS and Javascript into modconcat friendly URLs. Takes this: `{% cssconcat "{{ MEDIA_URL }}css/" %} <link href="{{ MEDIA_URL }}css/a.css" rel="stylesheet" type="text/css" /> <link href="{{ MEDIA_URL }}css/b.css" rel="stylesheet" type="text/css" /> <link href="{{ MEDIA_URL }}css/c.css" rel="stylesheet" type="text/css" /> {% endcssconcat %}` And outputs this: `<link href="/site_media/??a.css,b.css,c.css" rel="stylesheet" type="text/css" /> ` Similarly for javascript: `{% jsconcat "{{ MEDIA_URL }}js/" %} <script src="{{ MEDIA_URL }}js/a.js" type="text/javascript"></script> <script src="{{ MEDIA_URL }}js/b.js" type="text/javascript"></script> <script src="{{ MEDIA_URL }}js/c.js" type="text/javascript"></script> {% endjsconcat %}` becomes: `<script src="/site_media/??a.js,b.js,c.js" type="text/javascript"></script> `

  • javascript
  • css
  • modconcat
  • mod_concat
Read More

Template class to test custom tag libraries

TestableTemplate behaves just like django.template.Template, but you can give it a list of template.Libraries to load before parsing the template. This is equivalent to adding a bunch of {% load %} tags to the beginning of your template string, but you can use custom tag libraries which do not belong to Django applications' templatetags packages. This is occasionally useful in testing.

  • templates
Read More

Deep json serialization

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.

  • serialize
  • json
  • serialization
  • deep
Read More

DateTimeWidget using JSCal2

DateTimeWidget using [JSCal2](http://www.dynarch.com/projects/calendar/) Duplicate of [this snippet](http://www.djangosnippets.org/snippets/391/), but for latest 1.5 version of DHTML Calendar. Also here is **fixed problem of previous widget** linked to *form.changed_data* and *EntryLog.message*. This is fixed by adding own, little modified *_has_changed()* method

  • datetime
  • date
  • calendar
  • widget
  • dhtml
Read More

Redirect with change list with filters intact with admin actions

When using the django admin as a means of moderating reviews on a site, the obvious choice was to use admin actions and do everything from a single screen. The I stumbled across was that after the actions were peformed, the app redirected to the change list without any filters. This meant that filtering on un-moderated reviews was lost as soon as a change was made. It turns out that the solution is pretty simple, you just put a redirect to request.get_full_path() at the end of the admin action. I think this should be the default behaviour, but the fix is simple nonetheless.

  • admin
  • admin-actions
Read More

optparse dic action

An optparse action that let's you accept any parameters from the commandline. It stores them in another dictionary, inside the final options.

  • python
  • optparse
Read More

Auto-resolving a specific object from key string in url with decorator

If you use decorators to views, it will greatly improve readability and extensibility of your code. I'm using a couple of decorators like this to reduce complexity and redundancy in my view codes. `wraps` from Python 2.5's standard library make the attributes (name, docstring, and etc) of the decorated function same to those of `view_func` so that it could be easily recognized when you run `./manage.py show_urls` or debug.

  • views
  • decorator
Read More

Active User Sorted ModelAdmin

Since r7806, the `User` field is unsorted which makes it harder to find specific users in the list if there is more than a few. This snippet is an `django.contrib.admin.ModelAdmin` subclass which searches through all of the fields on a form and automatically sorts fields which have a relation with `User`. It also filters on having `active=True`. Just import the `SortedActiveUserModelAdmin` class in your `admin.py` and subclass your `ModelAdmin` classes from it instead of `admin.ModelAdmin`.

  • sorting
  • modeladmin
  • user-foreign-key
Read More