Login

Most bookmarked snippets

Snippet List

Updated - Template context debugger with (I)Pdb

Tag to inspect template context, filter to inspect variable. Originally by denis, [http://www.djangosnippets.org/snippets/1550/](http://www.djangosnippets.org/snippets/1550/). This just extracts variables from the context to locals for quicker access and autocompletion (When using ipdb). Additionally, 'vars' holds context keys for quick reference to whats available in the template.

  • template
  • debug
  • context
  • pdb
  • ipdb
Read More

email rendered via javascript (trick spam crawlers)

The proper looking email links rendered to the browser are not in the source code that way, and are rendered by javascript, so robots can't extract it. Its a trick way to have the email displayed properly without getting spamed as a result. Unless the robots are getting smarter, this has worked for me thus far.

  • template
  • email
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

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

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

Custom management command to list recent admin actions

On a busy site it can be nice to have a summary of admin activity. Running this command (I call it "adminlog") generates output like this: 2009-07-10 18:06:19: pbx changed flat page: "/yay/ -- Let's All Say Yay" By default it shows the last five actions; pass it a numerical arg to show more or fewer. Run this as a cron job and you can follow a site's admin-side activity without even logging in!

  • admin
  • commands
Read More
Author: pbx
  • 1
  • 3

slug filename

A one-liner that I use all the time: Set `upload_to` to something based on the slug and the filename's extension. Just add this function to the top of your models and use it like this: image = models.FileField(upload_to=slug_filename('people')) and the `upload_to` path will end up like this for eg `myfile.jpg`: people/this-is-the-slug.jpg Enjoy!

  • upload_to
Read More

RSS feed authentication

This is a very simple way of getting authenticated RSS feeds in django, by slightly changing the django.contrib.syndication.views 1) copy django/contrib/syndication/views.py into mysite/feeds/views.py 2) replace the contents of that file with the snippet 3) any feeds which you require login just add them to the auth_required list. In this case I require login for /feeds/mystuff/ so I make auth_required = ['mystuff'] My directory structure is like this: mysite/feeds/ views.py feedmodels.py feedmodels.py is just where you make your feed models (see http://docs.djangoproject.com/en/dev/ref/contrib/syndication/ where they give an example of "LatestEntries") [urls.py] - this is what I add in urls.py from mysite.feeds.feedmodels import Latest,MyPersonalStuff feeds = { 'latest':Latest, 'mystuff':MyPersonalStuff, } (r'^feeds/(?P<url>.*)/$', 'mysite.feeds.views.feed', {'feed_dict': feeds}), ###########################################################################

  • authentication
  • feed
  • rss
  • simple
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

Extended logging module

The django_admin_log only logs changes, not simple requests. Sometimes it can be useful to log when a user of your admin interface is checking out important data, for instance if you are making a system with personal sensitive data, that needs to comply with government / company policies. This will log such hits to the django_admin_log by overriding the change_view method in ModelAdmin. So you must override this method in all classes you want to have logged.

  • log
  • request
  • logging
  • django-admin
  • django_admin_log
  • extended
  • change_view
Read More

Improved model select field for generic relationships

Browse through the installed models using the content types framework. There are two difference in behavior with respect to the default field: 1. if a model provides a translation for its name (e.g.: verbose_name and/or verbose_name_plural), it shows that rather than a raw model name 2. allow to filter the models shown through the use of `choice` parameter Example: `mbf = ModelBrowseField(choices=['User', 'Session'])`

  • models
  • form
  • field
  • contenttypes
  • translation
  • browse
Read More

User groups template tag

This tag builds on top of the [ifusergroup/else tag](http://www.djangosnippets.org/snippets/390/), fixes a small bug and introduces support for else blocks. This adds a way to provide multiple groups via group1|group2|group3

  • tag
  • templatetag
  • user
  • auth
  • group
Read More

Counter model - run multiple persistent counters

Sometimes you just need to count things (or create unique-for-your-application IDs). This model class allows you to run as many persistent counters as you like. Basic usage looks like this: >>> Counter.next() 0 >>> Counter.next() 1L >>> Counter.next() 2L That uses the "default" counter. If you want to create and use a different counter, pass its name as a string as the parameter to the method: >>> Counter.next('hello') 0 >>> Counter.next('hey') 0 >>> Counter.next('hello') 1L >>> Counter.next('hey') 1L >>> Counter.next('hey') 2L You can also get the value as hex (if you want slightly shorter IDs, for use in URLs for example): >>> Counter.next_hex('some-counter-that-is-quite-high') 40e

  • database
  • counters
Read More

Test Server Thread

This class runs a django test server in another thread. This is very useful for e.g. selenium integration. Simple to integrate into django test framework. Usage: server = TestServerThread("127.0.0.1", "8081") server.start() # Run tests e.g. req = urllib.urlopen("http://127.0.0.1:8081") contents = req.read() server.stop() ps. I don't actually double space my code :). Not sure whats up with that!

  • thread
  • test
Read More

Simple Flatpage Navigation Items

Flatpages are great for simple html content. However, I wanted some way to associate a navigation menu (just a snippet of HTML) with one or more FlatPage objects. Additionally, I wanted to be able to edit these throught the Admin. This was my solution.

  • html
  • navigation
  • flatpage
  • nav
Read More

3110 snippets posted so far.