Login

All snippets written in Python

Snippet List

@url decorator improvements

A slight modification (and, I think, improvement) of the URL decorator found in [snippet 395](http://www.djangosnippets.org/snippets/395/). What's different between this snippet and 395? 1. We use `django.conf.urls.defaults.url()` when adding patterns 2. We support arbitrary arguments to the `url()` method (like `name="foo"`) 3. We _do not_ support multiple url patterns (this didn't seem useful to me, but if it is I can add it back.)

  • urls
  • url
  • decorator
  • decorators
  • urlpatterns
Read More

Persistent Params Decorator

This snippet helps preserving query parameters such as page number when the view perform redirects. It does not support hooking templates and contexts currently.

  • pagination
  • url
  • argument
Read More

Base64Field: base64 encoding field for storing binary data in Django TextFields

This Base64Field class can be used as an alternative to a BlobField, which is not supported by Django out of the box. The base64 encoded data can be accessed by appending _base64 to the field name. This is especially handy when using this field for sending eMails with attachment which need to be base64 encoded anyways. **Example use:** class Foo(models.Model): data = Base64Field() foo = Foo() foo.data = 'Hello world!' print foo.data # will 'Hello world!' print foo.data_base64 # will print 'SGVsbG8gd29ybGQh\n'

  • django
  • model
  • field
  • base64
  • blob
  • base64field
Read More

automatic urlpattern creator

This method creates urlpatterns based on view functions that have 'request' as their first parameter. See docstring for details.

  • url
  • urlconf
  • patterns
  • auto
  • urlpattern
Read More

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

Choices helper

A quick and dirty helper for model field `choices`. It's not perfect, but this is what I use.

  • models
  • choices
Read More

FeaturedModelChoiceField

Here is a way to get a drop down list from a queryset, with a list of "featured" items appearing at the top (from another queryset). This can be used for long select boxes which have a subset of commonly used values. The empty label is used as a separator and values can appear in both the featured set and the full set (it's more usable if they are in both). For example a country drop down list with 5 featured countries might look like this: Andorra Australia Kazakhstan Singapore Turkey ------------ Afghanistan Albania Algeria American Samoa Andorra Angola (hundreds more) To use this, define your form field like this: country = FeaturedModelChoiceField(queryset=Country.objects.all(), featured_queryset=Country.objects.featured())

  • fields
  • forms
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

CategoriesField

If you have a relatively small finite number of categories (e.g. < 64), don't want to add a separate column for each one, and don't want to add an entire separate table and deal with joins, this field offers a simple solution. You initialize the field with a list of categories. The categories can be any Python object. When saving a set of categories, the field converts the set to a binary number based on the indices of the categories list you passed in. So if you pass in as your categories list [A,B,C,D] and set model.categories = [C,D], the integer stored in the database is 0b1100 (note that although the categories list has a left-to-right index, the binary number grows right-to-left). This means that if you change the order of your category list once you have data in the DB, you'll need to migrate the data over to the new format. Adding items to the list should be fine however. If you need to do filtering based on this field, you can use bitwise operators. Django currently (to my knowledge) doesn't support this natively, but most DBs have some bitwise operator support and you can use the extra function for now. For example, this query will select CheeseShop models that have the 'Gouda' in its cheeses field. `CheeseShop.objects.all().extra(where=['cheeses | %s = cheeses'], params=[CHEESES.index('Gouda')])`

  • field
  • categories
  • binary
Read More

S/MIME Encrypted E-mail

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.

  • email
  • emailmessage
  • encryption
Read More

File storage with a better rename method

A file storage which uses a more sane rename method for existing files. Add `DEFAULT_FILE_STORAGE = 'site.storage.BetterNameFileSystemStorage'` (obviously changing `site.storage` to the module which you put this inside)

  • file-storage
Read More

Easy Form Structuring

With this, you can group form fields very easily. Since it does not create any html, you can use it not only to create fieldsets (with tables, lists, etc).

  • fieldset
  • form
  • field
  • grouping
  • structuring
Read More
Author: jug
  • -4
  • 3

Google Analytics Template Tag

Includes the Javascript for Google Analytics. Will not show Google Analytics code when DEBUG is on or to staff users. Use {% googleanalyticsjs %} in your templates. You must set something like GOOGLE_ANALYTICS_CODE = "UA-1234567-1" in your settings file. Assumes 'user' in your template variables is request.user, which it will be if you use: return render_to_response('template.html',{ }, context_instance=RequestContext(request)) (Assuming django.core.context_processors.auth is in TEMPLATE_CONTEXT_PROCESSORS, which it is by default)

  • google
  • urchin
  • analytics
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

Print Exceptions to the Console

Put this in an __init__.py somewhere that will be executed on initialization and all errors will be printed out to stderr. Useful for debugging Facebook apps, javascript calls, etc.

  • print
  • console
  • exception
  • signal
Read More

2956 snippets posted so far.