Login

All snippets written in Python

2956 snippets

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

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

Django app/project/directory po messages collector and pofile bulder

Some times if third party application is not translated competelly, developer have to extract and save all of **i18n** strings of third party application to current project, somewhere in root project directory (and configure additional `LOCALE_DIRS` entry) or in any project's applications (usually named "main" or same as project). And after, create **po** file by makemessages, completely translate it and compile it to **mo** file. This script allows you to extract all messages (`msgid`) from all **po** files and save it in **python** file in **django** format — `_("Some i18n message")`, and also compile complex **po** file, contained all **msgids** with related **msgstrs** of third party application. Full example: You have third party app, which is translated to russian, but not completely and names **blog**. It contains two locale dirs and have, for example, the following structure: blog ..locale ....ru ......LC_MESSAGES ........django.mo ........django.po ..contrib ....comments ......locale ........ru ..........LC_MESSAGES ............django.mo ............django.po ......__init__.py ......models.py ..__init__.py ..models.py ..urls.py ..views.py Each po file may contains any set of strings, which may be duplicated accross the application and any other po files, anyway result **po** file will be contain only unique **msgids** and **msgstrs**. This application installed by pip into virtualenv lib directory and of cource you do not want change code here. To translate this application in your project it is possible to copy all (unstanslated) strings to you project as `ugettext` entries (usually `_("Some i18n string")`), make **po** file, translate it and compile **mo** file. So, after call this script (for example, let it be named `pomessages.py`), you will get two files, **django.py** which contains all i18n strings and **django.po** which contains all **msgids** (i18n strings) with related translations. `pomessages.py path/to/third-party-app/root locale [project-name:default is empty] [filename:default=django]` In this case: `pomessages.py path/to/blog ru blog django` After script will be finished, in blog directory will be added two files, **django.po** and **django.mo**. **django.py** content: ... # blog:admin (source:ru) directory translations # ---------------------------------------------- _("Category") # blog:models.py:10, blog:views.py:15 _("Article") # blog:models.py:20 # blog:category/admin (source:ru) directory translations # ------------------------------------------------------- _("Add Category") # blog:category/admin/templates/admin/create.html:10 _("Edit Category") # blog:category/admin/templates/admin/change.html:20 ... **django.mo** content: ... # msgid "" msgstr "" "Project-Id-Version: Blog\n" "POT-Creation-Date: 2016-02-08 12:00+0000\n" "PO-Revision-Date: 2016-02-08 18:00+0000\n" #: path/to/file.py:10 msgid "Category" msgstr "Категория" #: path/to/file.py:20 msgid "Article" msgstr "" ... After you just need to place **py** file anywhere in your project and place **po** file to the following locale directory (or merge with existing **po** file if it exists), run: `django-admin makemessages -lru` to fix **po file** (remake it), translate missing entries and run: `django-admin compilemessages`, reload project and you will have translated third party application.

  • django
  • i18n
  • python
  • pofile
Read More