Login

All snippets

Snippet List

ModelChoiceField & ModelMultipleChoiceField with optgroups

Fields that support HTML optgroups. Adapted from [this snippet](https://djangosnippets.org/snippets/1968/) and updated to work with latest version of Django (1.9) and additional ModelMultipleChoiceField support added. Example Usage: tag = GroupedModelChoiceField(queryset=Tag.objects.all(), group_by_field='parent') positions = GroupedModelMultiChoiceField(queryset=Position.objects.all(), group_by_field='agency')

  • fields
  • optgroup
Read More

Crypt-SHA512 password hasher

Password hashing method using the crypt-sha512 algorithm, To be able to generate password compatible with the crypt-sha512 method avaiable in the standard crypt function since glib2.7 and used on modern linux distros. This provides compatibility with programs and systems that use the glibc crypt library for encrypting passwords (such as shadow passwords used by modern Linux distributions) while providing extra security than the regular crypt-sha1 mechanism (available in Django as CryptPasswordHasher) To use it you just need to add something like this to your django settings file: --- PASSWORD_HASHERS = [ 'utils.hashers.CryptSHA512PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.MD5PasswordHasher', 'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher', 'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher', 'django.contrib.auth.hashers.CryptPasswordHasher', ] --- You need to keep the standard hashers on the list to be able to convert existing passwords to the new method. The next time a user login after the modification the password will be converted automatically to first hasher on the list. Thanks mmoreaux for his improvements!!

  • password
  • hash
  • crypt
  • sha512
  • 1.9
Read More

Class based FileTypeValidator

A validator to check that an uploaded file has one of the given extensions. It **does not** check the MIME type/ any file contents. from django import forms from .validators import FileTypeValidator class UploadForm(forms.Form): csv_file = forms.FileField(label="Upload file", validators=[FileTypeValidator(('csv', 'txt'))])

  • validation
  • filefield
Read More

Generate iCal VTIMEZONE block with DAYLIGHT and STANDARD components, based on pytz zoneinfo data

In the last few days I spent a lot of time trying to find a library or repository of some kind that could help me generate the required DAYLIGHT and STANDARD components of ical VTIMEZONE blocks. Since I couldn't find anything, I cobbled together this snippet to poke around in pytz timezone information and output the bare minimum I needed to make my ICS files compliant and useful (DST transitions for this year and the next). I promise it's (superficially) tested against "real" ICS files, but that's all. UPDATE: Thanks to @ariannedee for a much improved version (see comment for details)

  • pytz
  • timezones
  • ical
  • icalendar
  • ics
Read More

Tag that parses dict like format and convert to classes like AngularJS

This tag is inspired by how ng-class works in AngularJS. https://docs.angularjs.org/api/ng/directive/ngClass **example:** `context = { 'context_var': True, 'context_var_2': 'a' }` `{% classes "class_name_1": context_var == True, "class_name_2": context_var_2 == "a", "class_name_3": False %}` output: **class_name_1 class_name_2**

  • tag
  • dict
  • ng-class
  • classes
Read More

Testing for pending migrations in Django

DB migration support has been added in Django 1.7+, superseding South. More specifically, it's possible to automatically generate migrations steps when one or more changes in the application models are detected. Definitely a nice feature! I've written a small generic unit-test that one should be able to drop into the tests directory of any Django project and that checks there's no pending migrations, ie. if the models are correctly in sync with the migrations declared in the application. Handy to check nobody has forgotten to git add the migration file or that an innocent looking change in models.py doesn't need a migration step generated. Enjoy!

  • testing
  • unittest
  • database
  • migration
Read More

django admin filter for GenericForeignKey field

Simple filter for django ModelAdmin How use: #models.py class ObjectWithGenericForeignKey(model.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object= GenericForeignKey('content_type', 'object_id', for_concrete_model=False) #admin.py class CommentAdmin(admin.ModelAdmin): list_filter = (get_generic_foreign_key_filter(u'Filter title'),)

  • filter
  • django
  • foreignkey
  • django-admin
Read More

Translate datetime format strings from Python to PHP

A simple Python function that converts a Python datetime formatting string to its nearest PHP equivalent. Python and PHP use different format string conventions when specifying datetime formats: * Python: [https://docs.python.org/2/library/time.html#time.strftime](https://docs.python.org/2/library/time.html#time.strftime) * PHP: [http://php.net/manual/en/function.date.php](http://php.net/manual/en/function.date.php) Working with Django the Date, Time and DateTime widgets all use Python format strings as stored in: * django.conf.global_settings.DATE_INPUT_FORMATS * django.conf.global_settings.TIME_INPUT_FORMATS * django.conf.global_settings.DATETIME_INPUT_FORMATS but if you want to use a datetime widget like the datetimepicker here: [http://xdsoft.net/jqplugins/datetimepicker/](http://xdsoft.net/jqplugins/datetimepicker/) then you'll find it uses PHP format specifiers. If you want Django and the datetimepicker to populate a field in the same way, you need to ensure they use the same format. So I add to the Django from context the default format as follows: `context["default_datetime_input_format"] = datetime_format_python_to_PHP(DATETIME_INPUT_FORMATS[0])` and in the template Javascript on my form for the datetimepicker i give it: `"format": {{default_datetime_input_format}}` and the datetimepicker now populates the the datetime field in the same format as Django.

  • datetime
  • date
  • format
  • time
Read More

JSON Web Token authentication middleware

This hasn't been thoroughly tested yet but so far it works great. We had no use for sessions or the built in authentication middleware for django as this was built to be a microservice for authentication. Unfortunately if you just use the django rest framework-jwt package the authentication occurs at the view level meaning request.user.is_authenticated() will always return False. We have a few internal non-api views that needed @login_required. We have a stripped down version of django that is very performant that we are using for microservices with built-in authorization using JSON Web Tokens. This service is authentication which has access to a `users` table. Any questions or curious how well lightweight django is working for microservices, or we he are doing the the authorization on the other services, or just improvements please drop a line - thanks.

  • middleware
  • authentication
  • json web token
  • django-rest-framework
  • JWT
Read More

3109 snippets posted so far.