Created
May 14, 2018 20:15
-
-
Save antnieszka/e2aca32cf9067f6d838046e42f6ed865 to your computer and use it in GitHub Desktop.
EnglishURLField
This file contains 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 django.db.models import CharField | |
from django.utils.text import slugify | |
import logging | |
logger = logging.getLogger(__name__) | |
class EnglishURLField(CharField): | |
def __init__(self, *args, **kwargs): | |
kwargs['max_length'] = kwargs.get('max_length', 2000) | |
kwargs['db_index'] = kwargs.get('db_index', True) | |
kwargs['unique'] = kwargs.get('unique', True) | |
self.populate_from = kwargs.pop('populate_from', None) | |
super(EnglishURLField, self).__init__(*args, **kwargs) | |
def pre_save(self, model_instance, add): | |
if getattr(model_instance, 'id', None): | |
# try to get previous slug/URL | |
current_page = model_instance.__class__.objects.get(id=model_instance.id) | |
previous_slug = getattr(current_page, self.name, None) | |
new_slug = getattr(model_instance, self.name, None) | |
if previous_slug and new_slug and previous_slug != new_slug: | |
assert type(new_slug) == str, 'slug is not a str!' | |
return new_slug | |
elif new_slug: | |
assert type(new_slug) == str, 'slug is not a str!' | |
return new_slug | |
slug_value = self.value_from_object(model_instance) | |
populate_from_field_value = getattr(model_instance, self.populate_from, None) | |
if not slug_value and populate_from_field_value: | |
slug_parts = [] if getattr(model_instance, self.populate_from, None) else [] | |
for parent in model_instance.get_ascendants(): | |
parent_name = getattr(parent, self.populate_from, None) | |
if parent_name: | |
slug_parts.insert(0, slugify(parent_name)) | |
logger.debug("Slugified parent {0} to {1}".format(parent, parent_name)) | |
else: | |
logger.debug("Parent {0} has no appropriate field or it is empty!".format(parent)) | |
final_slug = "/".join(slug_parts) | |
return final_slug |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment