Login

All snippets

Snippet List

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

reCAPTCHA integration

Integrating [reCAPTCHA](http://recaptcha.net/) with Django. **Warning**: although *remoteip* is used as optional parameter in this snippet, it is likely to become mandatory in the future. Please see [the comment by Jim Garrison](http://www.marcofucci.com/tumblelog/26/jul/2009/integrating-recaptcha-with-django/#comment-262) for more detail. Generic version of [this snippet](http://www.djangosnippets.org/snippets/433/). 1. Register on [reCAPTCHA](http://recaptcha.net/) to get your public/private key pair 2. Add your keys in settings.py 3. Add [recaptcha-client](http://pypi.python.org/pypi/recaptcha-client) to your project 4. Put ReCaptchaField and ReCaptcha widget somewhere (I've used a generic app `marcofucci_utils`) 5. Configure your form More information on my website [marcofucci.com](http://www.marcofucci.com/tumblelog/26/jul/2009/integrating-recaptcha-with-django/).

  • captcha
  • recaptcha
Read More

Decorator that limits request methods

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.

  • decorator
  • request
Read More

More information about users and groups in user admin

Based on [this snippet](http://www.djangosnippets.org/snippets/876/). More clean, with links to the related admin forms. Nice example on customization of contributed django admin apps. It adds the following to the user list interface: fields for is_superuser and is_staff, last login time; by default, short names of groups user is in (mousehover to see full names) It adds the following to the to group list interface: list of users in your groups. To enable, just put it somewhere and import it from your main urls.py: import utils/admin_auth.py

  • admin
  • customization
  • users
  • groups
  • roles
Read More

Hidden Date Display Widget for Admin

This is a custom widget for displaying a view only date field in the django admin. I used it to get around this ticket: [http://code.djangoproject.com/ticket/342](http://code.djangoproject.com/ticket/342)

  • admin
  • view
  • date
  • widgets
  • field
  • only
Read More

Media RSS generation for Photologue

Provides a basic implementation of Yahoo's [MediaRSS](http://video.search.yahoo.com/mrss) format for [Photologue](http://code.google.com/p/django-photologue/) galleries Simplest usage: I have feedgenerator.py in a utils directory. Import photofeeds and hook up the feed url in your URLConf: from utils.feedgenerator import photofeeds urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': photofeeds}),) Without customization, this will generate a feed for the gallery archive at `/feeds/gallery/` It will contain a single photo per gallery, as returned by Gallery.sample() Additionally, each gallery has a dynamic feed available at the url via Gallery.title_slug: `/feeds/gallery/gallery-title-slug/` This feed will contain an Item for each Photo in the Gallery All that is left is to add an autodiscovery feed to your pages in &lt;head&gt;. An RSS agent like CoolIris can then parse your gallery and provide a slick view of your photos. e.g Add something like this to gallery_detail.html: `<link rel="alternate" href="/feeds/gallery/{{ object.title_slug }}/" type="application/rss+xml" title="Photologue Gallery - {{ object.title }}" id="gallery_feed" /> `

  • feed
  • rss
  • photologue
  • syndication
Read More

3110 snippets posted so far.