Login

All snippets

Snippet List

Password Validation - Require Letters and Numbers - no regex

Simple password validation for user registration - requires that password be 7 or more characters and contain both letters and numbers. Original validation with regex approach developed by kurtis. Optimized no-regex version based on code from watchedman ran as fast or significantly faster on all systems on which we tested it.

  • registration
  • model
  • regex
  • user
  • validation
  • form
  • password
Read More

Chainable custom query manager for randomize.

This manager is based on the economical method of randomization. It usable in related models. For support this behavior required to be defined as default manger.

  • queryset
  • related-models
  • randomize
  • custom-manager
Read More

DownloadView generic class view

Generic class view to abstract out the task of serving up files from within Django. Recommended usage is to combine it with SingleObjectMixin and extend certain methods based on your particular use case. Example usage class Snippet(models.Model): name = models.CharField(max_length = 100) slug = SlugField() code = models.TextField() from django.views.generic.detail import SingleObjectMixin class DownloadSnippetView(SingleObjectMixin, DownloadView): model = Snippet use_xsendfile = False mimetype = 'application/python' def get_contents(self): return self.get_object().code def get_filename(self): return self.get_object().slug + '.py' '''

  • view
  • download
  • class-based-views
Read More

SelectRelatedManager

Because select_related() only works on ForeignKeys that are not null or blank, when you are customizing the admin, even if you set "list_select_related=True" you can still end up with way too many querys in the Admin changelist. By adding this code to your model you can decrease the queries dramatically. I found I needed this when I was working with Django apps with a lot of legacy data and I couldn't set the ForeignKey null=False.

  • admin
  • manager
  • select
  • queryset
Read More

Serve admin-media from urls.py

By default the `runserver` command does some magic to automatically serve admin media. This magic doesn't happen when using other servers like gunicorn… But this makes that magic unnecessary by using urls.py to route requests for admin media to the standard static media server. `#include <production_disclaimer.h>`

  • admin
  • admin-media
Read More

Multiple User subclasses custom Auth backend

A project I'm working on requires multiple different classes of users, all with different fields/attributes. Having a single UserProfile class with a generic relation was a complete pain in practice. So, I changed my classes to all subclass User directly and then used django-model-utils to create a custom ModelBackend that returns the appropriate class when accessing request.user. The InheritanceQuerySet manager provided by django-model-utils makes it all possible and with only a single database query. No need to add anything directly to the User class, by the way. Just subclass it directly with each of your custom classes: class CustomUser1(User): field1 = models.CharField(...) class CustomUser2(User): field2 = models.CharField(...)

  • user
  • profile
  • auth
  • subclass
  • backend
  • modelbackend
Read More

Duplicating Template Tag

This template tag will duplicate its contents according to a variable or integer supplied to it. {% duplicate 3 %}a{% endduplicate %} This would return: > aaa

  • template-tag
  • duplicate
  • loop
Read More

Math Captcha Field and Widget

This math captcha field and widget was inspired by Justin Quick's django-math-captcha, but I wanted to make it into one form field and not have anything in settings.py. I removed the division and modulo operators to avoid people having to input fractions, and just randomly select the operator. It leverages Django's built-in MultiValueField to set up the hidden hashed answer to compare the user's input to instead of rendering strings for the fields like django-math-captcha does. Unit tests soon to follow, but this is used in production at: http://btaylorweb.com/. Enjoy!

  • simple
  • captcha
  • field
  • widget
  • math
  • multiwidget
  • multifield
Read More

Newsletter email template

You can use this class for render and send html email message with the same logic and facility of website page creation. Just create an html template file with the same name of Class in lowercase.

  • template
  • email
  • newsletter
Read More

When you can't return a response object, throw it

There are cases when rendering had already started, but you have to return Your response nevertheless. A good example is when you have a django-cms plugin and a form in it. You want to redirect after the form was processed, but normally you can't do it. More information here: https://github.com/divio/django-cms/issues/79 http://groups.google.com/group/django-cms/browse_thread/thread/79ab6080c80bbcb5?pli=1

  • middleware
  • redirect
  • django-cms
Read More

View mixin and utils to generate PDF documents from html using xhtml2pdf

View mixin and utils to generate PDF documents from html using *xhtml2pdf*. The most interesting thing here is *PDFTemplateResponseMixin*. Adding this mixin to class based views allows automatic pdf generation using the view context and a customized template. There is also the lower level function *render_to_pdf*, similar to what can be seen in [snippet 659](http://djangosnippets.org/snippets/659/). See the docstrings for a detailed explanation.

  • pdf
  • mixin
  • class-based-views
Read More

Admin log entries management utils

A collection of utilities for admin log entries management. This module provides functions to add log entries for instance addition, change and deletion, as seen in *django.contrib.admin.options*. It also provides a class based view mixin to add logging capabilities, and other tools as a log collector. See docstrings for a better description.

  • admin
  • logentry
Read More

Manual CSRF check for Django Facebook canvas applications

The way to manually control CSRF correctness for FB applications. Automatic check cannot be used because FB does POST on your canvas URL when initializing your application without CSRF token. If you still want to use Django CSRF stuff do manual checks. You only need to perform manual check when there is no correct signed_request present in your request - correct request means you really deal with FB. Use facebook_csrf_check to verify POST requests when signed_request is absent.

  • django
  • python
  • post
  • facebook
  • csrf
  • fb
Read More

App Display Label Template Filter Workaround

I have been wrestling with custom app labels and have come to the conclusion that this is the easiest workaround for the problem. Since I name most of my apps as Foo_Bar this makes them look a lot nicer. I just apply the filter to whatever app label and it fixes it. If you need a more complex replacement, you could just have an if statement that looks for the full app label and replaces it with whatever you want.

  • template
  • filter
  • app-label
  • app-display
Read More

Configurable defaults for contrib.sites default Site during syncdb

This simple snippet provides a more sensible default for the Site object created during the first pass of syncdb (that is, with a default domain of `localhost:8000`). I made this so that the admin's "view on site" button will work automagically during my development cycle (which often involves dropping and recreating a sqlite database). In addition, it provides 2 options for configuring the default Site as you'd like: settings parameters (`DEFAULT_SITE_DOMAIN` and `DEFAULT_SITE_NAME`) or `kwargs` (the latter takes precedence).

  • django
  • admin
  • sites
  • syncdb
  • contrib
  • manage
  • Site
  • defaults
Read More

3110 snippets posted so far.