# -*- coding: utf-8 -*- from django.db import models, connection from hvad.models import TranslatableModel, TranslatedFields from bitfield import BitField # my models from directories.models import Iata from service.models import Service # from functions.db import db_table_exists #check if table exist and create flags if true flags = [str(item.id) for item in Service.objects.all()] if db_table_exists('service_service') else [] class City(TranslatableModel): """ Create City model Uses hvad.TranslatableModel which is child of django.db.models class """ services = BitField(flags=flags) url = models.SlugField(unique=True) #relations country = models.ForeignKey('country.Country', null=True, on_delete=models.PROTECT, related_name='cities') code_IATA = models.ForeignKey(Iata, blank=True, null=True) population = models.PositiveIntegerField(blank=True, null=True) phone_code = models.PositiveIntegerField(blank=True, null=True) #translated fields translations = TranslatedFields( name = models.CharField(max_length=50), transport = models.TextField(blank=True), description = models.TextField(blank=True), famous_places = models.TextField(blank=True), shoping = models.TextField(blank=True), #-----meta title = models.CharField(max_length=255), descriptions = models.CharField(max_length=255), keywords = models.CharField(max_length=255), ) #fields saves information about creating and changing model created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __unicode__(self): return self.lazy_translation_getter('name', self.pk) from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from django.conf import settings from functions.form_check import translit_with_separator from functions.translate import get_translated_fields @receiver(post_save) def city_post_save_handler(sender, **kwargs): """ objects saves two times: - first time Country object - second time CountryTranslation object object must have at least one Translation """ obj = kwargs['instance'] if isinstance(obj, City): # object is City # what languages must be all_langs = [code for code, lang in settings.LANGUAGES] # what languages are obj_langs = obj.get_available_languages() # missing_languages = list(set(all_langs) - set(obj_langs)) # get first Translation object translation = obj.translations.all()[0] # fields = get_translated_fields(obj) for code in missing_languages: # translate obj.translate(code) # go through all fields and set value for field in fields: setattr(obj, field, getattr(translation, field)) obj.save() if isinstance(obj, CityTranslation): # object is Translation print('trans') if obj.language_code == 'ru': city = City.objects.get(id=obj.master_id) country = city.country city.url = '%s-%s'%(translit_with_separator(country.name), translit_with_separator(obj.name)) city.save()