Login

All snippets

Snippet List

dict recurse template tag for django

Based on http://www.djangosnippets.org/snippets/592/, a simplified recurse template tag that will explore dict and list objects. Useful and straightforward for JSON documents (for instance from couchdb :p). Actual usage example: {% recursedict mydictionary %} <ul> {% loop %} <li>{% if key %}<b>{{ key }}</b>:&nbsp;{% endif %}{% value %}</li> {% endloop %} </ul> {% endrecurse %} The main tag syntax is "recursedict var" where var is your dictionary name. The "key" property will contain the current key, or None if the current value comes from a list (in other words the list (a, b, c) is handled like a very hypothetical {None: a, None: b, None: c} dictionary.) {% value %} will output the current value, or recurse if the value is a list, tuple or dict.

  • template
  • templatetag
  • json
  • dict
  • resurse
Read More

Breaking tests.py into multiple files

Django loads tests found in models.py and tests.py (if present) or actually a module or package named 'tests' under the app. Since tests can be a package, one can create a 'tests' directory, split the test cases across multiple files under 'tests' and import them from tests/__init__.py with: # tests/__init__.py from test_mod1 import * from test_mod2 import * ... from test_modN import * For a small number of files that's not too bad but it gets old as more files are added, plus it is error prone (e.g. test cases shadowing others with the same name). The snippet above simplifies the test splitting without importing everything into the same namespace. Typical usage: # tests/__init__.py from ... import get_suite suite = lambda: get_suite(__name__)

  • testing
  • tests
  • test
Read More

RML2PDF with Django

This is a django view that can return a PDF made using rml2pdf from reportlab. This RML is written with django templating system, to view the rml code and download a fully working version visit [reportlab](https://www.reportlab.com/software/documentation/sample-projects/rml-with-django/)

  • django
  • pdf
  • rml
  • reportlab
Read More

Security: Sideband information cover traffic middleware

This is a quick hack to address the SSL info leakage covered here: http://www.freedom-to-tinker.com/blog/felten/side-channel-leaks-web-applications Don't use this in prod without testing. :-) I'll get some feedback from django-dev and update here.

  • middleware
  • ssl
  • security
Read More

Generate Model Data. Lots of Options.

Generate model data with this django management command! Data is generated based off of the model field types. And will also correctly generate foreign key's to other randomly generated records for join tables. And generate images with random colors and random words in the image - for image fields. You can supply quite a few parameters that control how the data is generated. And you can control it per field, per model. Or you can supply your own callable function which you can return your own random data. **SEE THE DOCS / EXAMPLE IN THE CODE SNIPPET FOR AVAILABLE OPTIONS, AND HOW TO CONTROL GENERATED DATA PARAMETERS** You can generate data that looks like real content, without having to write fixtures and such. Just generate it! It can generate data for these types of fields: EmailField SlugField BooleanField DateField DateTimeField TimeField IntegerField DecimalField TextField CharField IPAddressField URLField SmallIntegerField PositiveSmallIntegerField PositiveIntegerField ImageField There are also a few callables included that you can use to generate this kind of data: zip, extended zip, hashkey and uuid It's also worth noting that I keep this project up to date on my own git repository. There are a few fonts you'll need if you want to generate imaages, included in my git repo. http://gitweb.codeendeavor.com/?p=dilla.git;a=summary

  • model
  • random
  • data
  • management
  • command
  • lipsum
Read More

ModelChoiceField with optiongroups

This is a ModelChoiceField where the choices are rendered in optiongroups (this is already posible with a normal Choicefield) For this to work properly the queryset you supply should already be ordered the way you want (i.e. by the group_by_field first, then any sub-ordering) See [related blog article](http://anentropic.wordpress.com/2010/03/23/django-optiongroups-for-your-modelchoice-field/)

  • modelchoicefield
  • optiongroup
Read More

Better Static Image Serving With Fallback

Serves images from a local directory, but if it doesn't find it locally, then go look for it on a server. This is useful for sites with very large amounts of static content. Instead of copying all your prod images to dev every time you update the database, simply use this in your URL patterns to serve the images: `(r'^(?P<path>.*)$', 'static_fallback.serve', {'document_root' : '/path/to/my/files/'})` By default, it caches the images locally in the path it was supposed to find them. The fallback server URL can be specified in urls.py or settings as FALLBACK_STATIC_URL. Thanks to Johnny Dobbins for the idea. Based on the Nginx pass through image proxy concept. For more info [http://menendez.com/blog/using-django-as-pass-through-image-proxy/](http://menendez.com/blog/using-django-as-pass-through-image-proxy/)

  • image
  • static
  • images
  • fallback
Read More

Template tag which gets specific GET variables from the current request

This template tag attempts to get specific GET variables from request.GET. If such variables exist, it shows them as a query string (with optional "include_ampersand" mode when it puts an "&" at the end if there is a result string, or a "?" if there's none: it is used when you need to add a new variable to the query string) or as hidden input fields ("html_form" mode).

  • get
  • template-tag
  • request
  • variables
  • get-variables
Read More

Subdirectory and subcontext include template tag with examples

In principle it's a DRY code of a template node that can be used for creating project-wide template-tags. These can be used to display conceptually common blocks in templates with applications specific looks and content. E.g.: 1. application-specific info message, 2. model instances details in the list context, 3. login messages like 'Please login or signup to [some app-dependent text]' with appropriate url's, 4. standard forms (e.g with same CSS classes, displayed with uni_form). The code is profusely commented so look it up for details. Basically, when you have your project-wide `SubIncludeNode` tag defined, then just define appropriately named templates in applications template subdirectories e.g. `'profiles/_show_item.html'`. ** Example usage: login or signup message ** Let's say we are editing template rendered by the view indicated by the pattern named 'project_list' in the 'projects' app: {# those are equivalent #} {% login_or_signup %} {% login_or_signup project_list %} {% login_or_signup "project_list" %} {# academic purposes direct sub_include usage #} {# those two includes are also equivalent if there is no template called '_login_or_signup.html' in the 'projects' subdirectory #} {% url acct_signup as signup_url %} {% url acct_login as login_url %} {% url project_list as next_url %} {% sub_include "_login_or_signup.html" %} {% include "_login_or_signup.html" %} {# and those two are also equivalent if there is a template called '_login_or_signup.html' in the 'projects' subdirectory #} {% sub_include "_login_or_signup.html" from "projects" %} {% sub_include "_login_or_signup.html" %} {# also equivalent include if there is no variable called 'projects' in tempalte's context #} {% sub_include "_login_or_signup.html" from projects %} {# those are examples of using custom subcontext #} {% url acct_signup as signup_url %} {% url acct_login as login_url %} {% sub_include "_login_or_signup.html" from "default" with login_url,signup_url,next_url="/welcome" %} {% sub_include "_login_or_signup.html" with login_url="/login",next_url="/welcome",signup_url="/signup" %} ** Mored advanced usage proposal ** Say you have an subclasses of some model from the original app in a separate extending apps. You want to display subclasses instances differently using the original app templates. In the original app you do not know what the set of subclasses is (as the original app is not aware of the extending apps). Subclassing the `SubIncludeNode` you can override the `default_subdir` method such that it returns the app label of a model instance that was passed as a argument of your tag. This way you just put templates like `_show_instance.html` in extending apps subdirectories and voila - you have implementation of the overrideable templates displaying appropriately details about the model subclass instances.

  • templatetag
  • templatetags
  • include
Read More

django-admin custom filter: IS NULL/IS NOT NULL

A simple django-admin filter to allow a boolean-like filter for IS NULL/IS NOT NULL. By default it applies to CharField, IntegerField, and FileField, but you can change this by editing NullFilterSpec.fields.

  • filter
  • admin
  • null
  • filterspec
Read More

Output sql_queries in Firebug console when in debug mode

Add this code to the end of the `<body>` of your main template and it will print out all your SQL queries with timings in the Firebug console. This uses the "django.core.context_processors.debug" template context processor, which requires that DEBUG=True and that your IP address is listed in INTERNAL_IPS.

  • sql
  • debug
  • console
  • firebug
  • sql_queries
Read More

IPAddressField with CIDR support

Based on #1381 Use this piece of code to add IPv4/IPv6 and network support to Django. An IPAddressField allows you to find IP's for a given subnet. An IPNetworkField allows you to find a subnet for a given IP or find a subnet within a subnet. For starters, simply paste it into a new file in your app called fields.py. IPAddressField example # models.py from fields import IPAddressField class IPTest(models.Model): ip = IPAddressField() To search for an IP within a given subnet from ipaddr import IPNetwork IPTest.objects.filter(ip__in=IPNetwork('10.0.0.0/24')) IPNetworkField example # models.py from fields import IPNetworkField, IPNetworkQuerySet class IPTest(models.Model): objects = IPNetworkQuerySet.as_manager() network = IPNetworkField() To search for a subnet with a given IP from ipaddr import IPAddress IPTest.objects.network('network', IPAddress('10.0.0.1'))

  • cidr
  • ipv4
  • ipv6
  • ipaddress
  • ipnetwork
Read More

login on activation with django-registration

Here's a signal handler to log a user in on registration activation. It took me an hour to figure out that I needed to put the user.backend in quotes and google wasn't being my friend. from [the django-registration documentation](http://docs.b-list.org/django-registration/0.8/faq.html): How do I log a user in immediately after registration or activation? You can most likely do this simply by writing a function which listens for the appropriate signal; your function should set the backend attribute of the user to the correct authentication backend, and then call django.contrib.auth.login() to log the user in.

  • login
  • auth
  • django-registration
Read More

3109 snippets posted so far.