Skip to content

Instantly share code, notes, and snippets.

@stephenmcd
Created December 11, 2013 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenmcd/7917262 to your computer and use it in GitHub Desktop.
Save stephenmcd/7917262 to your computer and use it in GitHub Desktop.
Calculated RTL field handling in Django Rest Framework.
from unicodedata import bidirectional
from django.template.defaultfilters import striptags
from rest_framework import serializers
class RTLField(serializers.BooleanField):
def __init__(self, *args, **kwargs):
kwargs.setdefault("read_only", True)
super(RTLField, self).__init__(*args, **kwargs)
def to_native(self, value):
value = striptags(value).replace(" ", "")[:100]
score = sum([bidirectional(c) in ("R", "AL") for c in value])
return bool(score and score >= (len(value) / 2))
#
# Usage:
#
# class MySerializer(serializers.ModelSerializer):
#
# class Meta:
# model = MyModel
# fields = ("id", "title", "content", "title_rtl", "content_rtl")
#
# title_rtl = RTLField(source="title")
# content_rtl = RTLField(source="content")
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment