dizballanze

Untitled

Apr 24th, 2013
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.36 KB | None | 0 0
  1. @receiver(post_save, sender=CompanyInfo)
  2. def create_url_company(sender, instance, created, **kwargs):
  3.     """
  4.    Run from CompanyInfo ( post_save signals )
  5.  
  6.    Set new url path or add new path
  7.    """
  8.     if instance.is_approved and instance.is_valid:
  9.         slug_name = slugify(instance.name)  # Company Name to URI string
  10.  
  11.         create_url_show = lambda slug, company: reverse('company_profile_info',  kwargs=dict(company_name=slug))
  12.         create_url_report = lambda slug, company: reverse('report-company-scam',  kwargs=dict(company_name=slug))
  13.         create_url_complaints = lambda slug, company: reverse('company-complaints',
  14.                                              kwargs=dict(company_name=slug,
  15.                                                 cat=company.category.slug if company.category else 'none'))
  16.  
  17.         actions = {'show': create_url_show,
  18.                    'complaints': create_url_complaints,
  19.                    'report': create_url_report}
  20.  
  21.         if instance.slug == slug_name:
  22.             del actions['show']
  23.             del actions['report']
  24.  
  25.         for create_url, action in actions.iteritems():
  26.             slug = instance.slug if instance.slug else ''
  27.  
  28.             content_type = ContentType.objects.get_for_model(instance)
  29.  
  30.             # check exists url for other objects
  31.             new_slug = slug_name
  32.             i = Url.objects.filter(content_type=content_type,
  33.                     action=action, path=create_url(new_slug, instance))\
  34.                     .exclude(object_id=instance.pk).count()
  35.             if i:
  36.                 new_slug = '%s_%d' % (slug_name, i)
  37.  
  38.             # get or create new url object for CompanyInfo instance
  39.             new_url, is_created = Url.objects.get_or_create(content_type=content_type, action=action,
  40.                                                 path=create_url(new_slug, instance), object_id=instance.pk)
  41.             if not is_created:
  42.                 # if url was exists cancel redirect
  43.                 Url.objects.filter(pk=new_url.pk).update(redirect=Url.DIRECT)
  44.  
  45.             # set redirect mode (301) for other exists url for this object CompanyInfo
  46.             Url.objects.filter(content_type=content_type, action=action, object_id=instance.pk)\
  47.                 .exclude(pk=new_url.pk)\
  48.                 .update(redirect=Url.MOVED_PERMANENTLY)
  49.  
  50.             CompanyInfo.objects.filter(pk=instance.pk).update(slug=new_slug)
Advertisement
Add Comment
Please, Sign In to add comment