Login

Most bookmarked snippets

Snippet List

Django Rest Framework LoginExemptPermission: Apply `IsAuthenticated` to all ViewSet actions except those specified as exempt of authentication

Say you want to keep your API secure and thus it has authentication, but there's this one View action in a ViewSet which unlike the rest of the ViewSet's actions needs to allow free access without authentication. This solution applies the good old `IsAuthenticated` permission to all ViewSet actions except those defined in a `login_exempt_actions` list. That's a list of the ViewSet action's names. This is a simple solution for this particular problem, which I imagine could be quite common. Any case where the requirements are more complex should implement one of the DRF permissions extensions which allow for the use of logical operators. **NOTE**: Remember that `request.user` will be an `AnonymousUser` instance, so be careful with any code which assumes it'll be a `User` instance. This could be the case with, say, a custom `get_queryset` implementation.

  • authentication
  • api
  • django-rest-framework
Read More

AvaliabilityAtDateListFilter

If your model have two dates, start and end of something, you may want to have filter which allow you to show objects which last on specific day.

  • filter
  • admin
  • changelist
  • list_filter
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

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

3110 snippets posted so far.