Login

All snippets written in Python

Snippet List

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

Relative paths for Django template tags 'extends' and 'include'.

[The problem](http://stackoverflow.com/questions/671369/django-specifying-a-base-template-by-directory): {% extends "./../base.html" %} won't work with extends. It causes a lot of inconvenience, if you have an extensive hierarchy of django templates. This library allows relative paths in argument of 'extends' and 'include' template tags. Relative path must start from "./" Just write in your templates as follows: ``` {% load relative_path %} {% extends "./base.html" %} ``` this will extend template "base.html", located in the same folder, where your template placed ``` {% load relative_path %} {% extends "./../../base.html" %} ``` extend template "base.html", located at two levels higher same things works with 'include' tag. ``` {% load relative_path %} {% include "./base.html" %} ``` include base.html, located near of your template. **Warning!** The rule 'extends tag must be first tag into template' is disabled by this library. Write your template with caution. **Compatibility** Code was tested with Django versions from 1.4 to 1.9 Installation. ------------- Installation is differs for Django version 1.9 and previous versions, because 1.9 brings many changes into template's mechanizm. **Django 1.9** Plug reference to library code in 'TEMPLATES' key of settings.py or django.settings.configure() ``` TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(ROOT_PROJECT, 'tpl').replace('\\', '/')], 'OPTIONS': { 'loaders': [ 'dotted_path_to_relative_path_file.FileSystem19', 'dotted_path_to_relative_path_file.AppDirectories19', ], 'libraries': { 'relative_path': 'dotted_path_to_relative_path_file', }, }, }] ``` **Django 1.4/1.8** Put 'relative_path.py' file to the 'templatetags' folders of your app. (app must be included into INSTALLED_APPS tuple) In settings.py or django.settings.configure(), replace standard django template loaders by loaders from this library ``` TEMPLATE_LOADERS = ( 'dotted_path_to_relative_path_file.FileSystem', 'dotted_path_to_relative_path_file.AppDirectories', ) ```

  • template
  • extends
  • custom-tag
  • include
  • relative-path
Read More

Building an RSS feed for Django

This RSS using `Rss201rev2Feed` from Django. And we found it from source code of blog.pythonanywhere.com: https://github.com/pythonanywhere/jab/blob/master/jab/feeds.py Demo: http://django.id/blog/feed/

  • Django
  • RSS feed
  • RSS
Read More

2955 snippets posted so far.