# -*- coding: utf-8 -*- from django.db import models from hvad.models import TranslatableModel, TranslatedFields, TranslationManager from django.template.defaultfilters import slugify import copy class ArticleManager(TranslationManager): def safe_get(self, **kwargs): model = self.model try: return model.objects.get(**kwargs) except: return None class Article(TranslatableModel): """ Create Article model Uses hvad.TranslatableModel which is child of django.db.models class """ #set manager of this model objects = ArticleManager url = models.SlugField(unique=True) theme = models.ManyToManyField('theme.Theme') tag = models.ManyToManyField('theme.Tag', related_name='tags',blank=True, null=True) user = models.ForeignKey('accounts.User', verbose_name='Автор', on_delete=models.PROTECT, related_name='articles') #translated fields translations = TranslatedFields( main_title = models.CharField(max_length=100), preview = models.TextField(), description = models.TextField(), #-----meta title = models.CharField(max_length=255, blank=True), descriptions = models.CharField(max_length=255, blank=True), keywords = models.CharField(max_length=255, blank=True), ) def __unicode__(self): return self.lazy_translation_getter('main_title', self.pk) def clone(self): """ Return an identical copy of the instance with a new ID. """ if not self.pk: raise ValueError('Instance must be saved before it can be cloned.') duplicate = copy.copy(self) # Setting pk to None. Django thinking this is a new object. duplicate.pk = None # url must be unique duplicate.url += '_copy' if Article.objects.safe_get(url=duplicate.url): #already has copy this instance return duplicate.save() # but lost all ManyToMany relations and Translations. # copy relations for field in self._meta.many_to_many: source = getattr(self, field.attname) destination = getattr(duplicate, field.attname) for item in source.all(): destination.add(item) # copy translations languages = self.get_available_languages() ignore_fields = ['id', 'master', 'language_code'] for code in languages: duplicate.translate(code) tr = self._meta.translations_model.objects.get(language_code = code,master__id=self.pk) for field in duplicate._translated_field_names: if field in ignore_fields: continue setattr(duplicate, field, getattr(tr, field)) duplicate.save() return duplicate