Login

Most bookmarked snippets

Snippet List

Raw include from static dir tag

This is useful when you don't want to put any `{% verbatim %}` tag in the file(s) you're including within template(s) (because you want it/them completely raw) and when you want to load such file(s) from static dir(s), as native `{% include %}` tag can't achieve that (still). Put the provided code in *templatetags/rawinclude.py* in your Django app, and then use it in your template(s) like this: `{% load rawinclude %}{% raw_include 'file.html' %}`

  • include
  • verbatim
  • raw
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

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

Django EncryptedField

Inspired by [Base64Field: base64 encoding field for storing binary data in Django TextFields](https://djangosnippets.org/snippets/1669/) but in a generic way. from django.db import models import base64 class Base64Encryptor(object): def encrypt(self, value): return base64.encodestring(value) def decrypt(self, msg): return base64.decodestring(msg) class MyModel(models.Model): ... b64_data = EncryptedField(encryptor=Base64Encryptor) ... # Usage my_obj = MyModel() my_obj.b64_data = "hello" print(my_obj.b64_data) # will output 'hello' print(my_obj.b64_data_enc) # will output 'aGVsbG8=\n'

  • django
  • fields
  • encryption
Read More

Filter changelist by a numeric field using a number of common value ranges

## How to use Use this [admin filter](https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter) together with a numeric field to allow filtering changlist by field values range (in this case, age groups): For example, to group customers by age groups: class Customer(models.Model): # ... age = models.IntegerField() age.list_lookup_range = ( (None, _('All')), ([0, 2], '0-2'), ([2, 4], '2-4'), ([4, 18], '4-18'), ([18, 65], '18-65'), ([65, None], '65+'), )) class CustomerAdmin(admin.ModelAdmin): list_filter = [('age', ValueRangeFilter), ] ## Inspiration [This snippet](https://djangosnippets.org/snippets/587/) (for django < 1.4) inspired me to make this work for newer django versions.

  • filter
  • admin
  • field
  • range
Read More

Compare objects list and get a list of object to inserted or updated

**Problem** You have an input `json` with which you will create a list of objects, you have to validate that the object will be created if it not exists, if exists determine whether to upgrade or discard depending of they have not undergone any changes. Solution 1) With the input `json` will be created the list of objects of the class that we insert or updatee 2) Read all fields in the database, using one of the fields as key to creating a dictionary with the objects in the database 3) Compare the objects and determine if it will be updated, inserted or discarded Django problem: by default only compares the level objects using the primary key (id). Compare field by field is the solution to determine if the object has changed. hints: The _state field is present in every object, and it will produce a random memory location, You can find cache fields so you need to remove these begins with underscore `_`. The fields excluded can be fk, and these fields produce field_id, so you will needs to exclude it class Country(models.Model): # country code 'MX' -> Mexico code = models.CharField(max_length=2) name = models.CharField(max_length=15) class Client(models.Model): # id=1, name=pedro, country.code=MX, rfc=12345 name = models.CharField(max_length=100) country = models.ForeignKey(Country) rfc = models.CharField(max_length=13) Country.objects.create(**{'code': 'MX', 'name': 'Mexico'}) # creating the country Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':12345}) # creating the client obj_db = Client.objects.get(id=1) country = Country.objects.get(code='MX') obj_no_db = Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':12345}) obj_db == obj_no_db # True obj_no_db = Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':1}) obj_db == obj_no_db # True # but isn't True because the rfc has change, how can compare field by field obj_db.rfc == obj_no_db.rfc # False, I was expected this result when compare obj_db == obj_no_db because they are not equal **Solution to compare field by field** _obj_1 = [(k,v) for k,v in obj_db.__dict__.items() if k != '_state'] _obj_2 = [(k,v) for k,v in obj_no_db.__dict__.items() if k != '_state'] _obj_1 == _obj_2 # False This is only for one object, and you can include in `__eq__` method in your model, but what happen if you need compare a list of object to bulk for insert or update with `django-bulk-update`. Well my snipped pretends solve that. so **How can use it.** obj_list = [<Object Client>, <Object Client>, <Object Client>, <Object Client>] get_insert_update(Client, 'id', obj_list) exclude_fields = ['country'] get_insert_update(Client, 'id', obj_list, exclude_fields=exclude_fields)

  • models
  • bulk
Read More

@group_required decorator

Use : `@group_required(('toto', 'titi'))` `def my_view(request):` `...` `@group_required('toto')` `def my_view(request):` `...` Note that group_required() also takes an optional login_url parameter `@group_required('toto', login_url='/loginpage/')` `def my_view(request):` `...` As in the login_required() decorator, login_url defaults to settings.LOGIN_URL. If the raise_exception parameter is given, the decorator will raise PermissionDenied, prompting the 403 (HTTP Forbidden) view instead of redirecting to the login page. Such as https://docs.djangoproject.com/en/1.8/topics/auth/default/#the-permission-required-decorator **Inspired by** : https://github.com/django/django/blob/stable/1.8.x/django/contrib/auth/decorators.py

  • decorator
  • login
  • auth
  • decorators
  • group_required
  • @group_required
Read More

Combined CreateView and UpdateView

By combining the CreateView and UpdateView, you can significantly reduce repetition when processing complex forms (for example, with multiple inline formsets), by only writing the get_context_data and form_valid functions once. This class can be used just like a normal CreateView or UpdateView. Note that if you're trying to use it as an UpdateView but it cannot find the requested object, it will behave as a CreateView, rather than showing a 404 page.

  • generic-view
  • class-based-generic-view
  • UpdateView
  • CreateView
Read More

3110 snippets posted so far.