Login

3110 snippets

Snippet List

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

REMOVE IMAGEFIELD ATTACHMENT IN DJANGO

File cleanup callback used to emulate the old delete behavior using signals. Initially django deleted linked files when an object containing a File/ImageField was deleted. Usage: >>> from django.db.models.signals import post_delete >>> post_delete.connect(file_cleanup, sender=MyModel, dispatch_uid="mymodel.file_cleanup")

  • filefield
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

Database Routing by URL

An example of how to select the "default" database based on the request URL instead of the model. The basic idea is that the middleware `process_view` (or `process_request`) function sets some context from the URL into thread local storage, and `process_response` deletes it. In between, any database operation will call the router, which checks for this context and returns an appropriate database alias. In this snippet, it's assumed that any view in the system with a `cfg` keyword argument passed to it from the urlconf may be routed to a separate database. Take this urlconf for example: `url( r'^(?P<cfg>\w+)/account/$', 'views.account' )` The middleware and router will select a database whose alias is `<cfg>`, or "default" if none is listed in `settings.DATABASES`, all completely transparent to the view itself.

  • multidb database router url
Read More

replace

Small example of how to write your own function. This is not available in Django. The function just replaces static text strings, regular expressions are not supported. The syntax is the same in SQLite, PostgreSQL, MySQL and Oracle.

  • text
  • replace
Read More

Django chunked queryset iterator

The function slices a queryset into smaller querysets containing chunk_size objects and then yield them. It is used to avoid memory error when processing huge queryset, and also database error due to that the database pulls whole table at once. Concurrent database modification wouldn't make some entries repeated or skipped in this process.

  • django
  • python
  • database
  • queryset
  • iterator
  • memoryerror
Read More

Pre-delete signal function for deleting files a model

This snippit is meant to be used with the pre_delete signal to delete any files associated with a model instance before the instance is deleted. It will search the model instance for fields that are subclasses of FieldFile, and then delete the corresponding files. As such, it will work with any model field that is a subclass of FileField.

  • remove
  • delete
  • signals
  • file
Read More

CNPJ and CPF Validation for Models

The code was placed inside a helper file without using a class. The Django validator was not designed to work with validator classes, it would appear, so retrieving the value from the field proved to be a hassle. Just create a helper file, import it on your model, and use the validator in the standard way, as such: cnpj = models.CharField(unique=True, max_length=14, validators=[validate_CNPJ]) cpf = models.CharField(unique=True, max_length=14, validators=[validate_CPF])

  • model
  • validation
  • cnpj
  • cpf
Read More

Simply Gravatar Templatetags

Simply Gravatar Templatetags, for example the name of this templatetag is: `templatetags/gravatar_tags.py`, this supported for Python2 or Python3.

  • django
  • image
  • templatetag
  • gravatar
Read More

Template tag for stripping blank lines

When writing clean and easy-to-read templates, it's usually good to have structural template tags (e.g. {%for%}, {%if%}) alone on their own line with proper indentation. When such a template is rendered, the resulting HTML will have blank lines in place of the template tags. The leading blank space used for indentation is also intact. This template tag strips all empty and all-whitespace lines when rendering the template. Be careful not to apply it when not intended, e.g. when empty lines are wanted inside PRE tags.

  • template
  • html
  • strip
  • empty
  • blank
Read More

CSVField for forms

FileField that checks that the file is a valid CSV and if specified in `expected_fieldnames` checks that the fields match exactly. The widget's `accept` parameter is set to accept csv, text and excel files. **TODO**: Validate the entirety of the CSV file, not just the headers. But this should be enough for most use cases, as checking the whole file could be computationally expensive for huge files. Example usage: people = CSVField(expected_fieldnames=['First Name', 'Last Name'])

  • forms
  • csv
  • field
Read More