Created
December 11, 2013 19:54
-
-
Save stephenmcd/7917262 to your computer and use it in GitHub Desktop.
Calculated RTL field handling in Django Rest Framework.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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