def handle(self, *args, **options):
     for filename in args:
         self.stdout.write("Reading {}".format(filename))
         defaults = parse(filename)
         categories = defaults.pop('categories')
         slug = defaults.pop('slug')
         #print(title)
         #print(categories)
         #pprint(defaults)
         # Implement update_or_create only available when 1.7 is out.
         try:
             post = Post.objects.get(slug=slug)
             for key, value in defaults.items():
                 setattr(post, key, value)
             post.save()
             self.stdout.write("Updated article {}".format(post.title))
         except Post.DoesNotExist:
             defaults.update({'slug': slug})
             post = Post(**defaults)
             post.save()
             self.stdout.write("Created article {}".format(post.title))
         for cat_name in categories:
             try:
                 post.categories.get(name=cat_name)
                 self.stdout.write("Found category {}.".format(cat_name))
             except Category.DoesNotExist:
                 try:
                     category = Category.objects.get(name=cat_name)
                     post.categories.add(category)
                     self.stdout.write(
                         "Assigned category {}.".format(cat_name)
                         )
                 except Category.DoesNotExist:
                     post.categories.create(name=cat_name)
                     self.stdout.write(
                         "Created category {}".format(cat_name)
                         )
         # Now do the redirects.
         # the Redirect model has an old_path, a new_path, and a site_id.
         # use settings.SITE_ID
         old_path = "/blogue/" + post.slug + ".html"
         new_path = "/blogue/" + post.slug + "/"
         defaults = {
             'site_id': settings.SITE_ID,
             'old_path': old_path,
             }
         try:
             redirect = Redirect.objects.get(**defaults)
             redirect.new_path = new_path
             redirect.save()
             self.stdout.write(
                 "Updated redirect {} ==> {}".format(old_path, new_path)
                 )
         except Redirect.DoesNotExist:
             defaults.update({'new_path': new_path})
             redirect = Redirect(**defaults)
             redirect.save()
             self.stdout.write(
                 "Created redirect {} ==> {}".format(old_path, new_path)
                 )
Exemplo n.º 2
0
def reslug(modeladmin, request, queryset):
    """
    admin action to reset the slug of an entry

    creates a redirect too

    - If the slug hasnt changed, do nothing
    - If the redirect already exists, don't create a new redirect
    - If there is a redirect that will send this into a loop,
        remove that redirect and create a new one
    """
    for obj in queryset:
        old_url = obj.get_absolute_url()

        obj.slug = None
        obj.save()

        if old_url != obj.get_absolute_url():
            try:
                redirect = Redirect.objects.get(site=get_current_site(request), old_path=old_url, new_path=obj.get_absolute_url())
            except ObjectDoesNotExist:
                try:
                    looping_redirect = Redirect.objects.get(site=get_current_site(request), old_path=obj.get_absolute_url(), new_path=old_url)
                    looping_redirect.delete()
                except ObjectDoesNotExist:
                    pass
                redirect = Redirect(site=get_current_site(request), old_path=old_url, new_path=obj.get_absolute_url())
                redirect.save()
Exemplo n.º 3
0
def create_redirect(sender, instance, raw, **kwargs):

    # Only proceed if not raw, we're dealing with an existing object, and the
    # contrib redirects app is installed.
    if not raw and instance.pk \
            and 'django.contrib.redirects' in settings.INSTALLED_APPS:

        from django.contrib.redirects.models import Redirect

        # Only proceed if an existing object exists
        try:
            existing = sender.objects.get(pk=instance.pk)
        except sender.DoesNotExist:
            return

        existing_path = existing.get_absolute_url()
        new_path = instance.get_absolute_url()

        if hasattr(instance, 'site') and existing.site != instance.site:
            new_path = '//{0}{1}'.format(instance.site.domain, new_path)

        if existing_path != new_path:
            try:
                redirect = Redirect.objects.get(site=existing.site,
                                                old_path=existing_path)
            except Redirect.DoesNotExist:
                redirect = Redirect(site=existing.site, old_path=existing_path)
            redirect.new_path = new_path
            redirect.save()
Exemplo n.º 4
0
 def _setup_redirect(self, old, new):
     if old != new:
         try:
             r = Redirect(site=self.conf['pages']['site'],
                          old_path=old,
                          new_path=new)
             r.save()
         except:
             self.logger.warn("Could not setup redirect %s to %s " %
                              (old, new))
Exemplo n.º 5
0
 def _setup_redirects(self, page):
     """
     Setup redirects for new URLs
     """
     for url in self.document.old_urls():
         if url != page.url:
             r = Redirect(site=self.conf['pages']['site'],
                          old_path=url,
                          new_path=page.url)
             r.save()
Exemplo n.º 6
0
def drupal_redirect_django(path, post):
    from django.contrib.redirects.models import Redirect
    from django.contrib.sites.models import Site
    current = Site.objects.get_current()
    if path:
        dst = '/' + path.dst.strip('/') + '/'
        r = Redirect(site=current, old_path=dst, new_path='/example'+post.get_absolute_url())
        r.save()
        src = '/' + path.src.strip('/') + '/'
        r = Redirect(site=current, old_path=src, new_path='/example'+post.get_absolute_url())
        r.save()
Exemplo n.º 7
0
 def forwards(self, orm):
     # XXX use the first site
     site = Site.objects.all()[0]
     old_path = '/verify/'
     new_path = '/racks/'
     if len(Redirect.objects.filter(old_path=old_path)) == 0:
         redirect = Redirect(old_path=old_path,
                             new_path=new_path,
                             site=site,
                             )
         redirect.save()
 def forwards(self, orm):
     # XXX use the first site
     site = Site.objects.all()[0]
     old_path = '/verification-kit/'
     new_path = '/tools-and-tips/'
     if len(Redirect.objects.filter(old_path=old_path)) == 0:
         redirect = Redirect(old_path=old_path,
                             new_path=new_path,
                             site=site,
                             )
         redirect.save()
Exemplo n.º 9
0
    def save(self, *args, **kwargs):
        if hasattr(self, 'get_absolute_url'):
            model = self.__class__
            if self.pk is not None:
                old_object = model.objects.get(pk=self.pk)
                if old_object.slug != self.slug:
                    redirect = Redirect(site=self.site,
                                        old_path=old_object.get_absolute_url(),
                                        new_path=self.get_absolute_url())
                    redirect.save()

        super(Slugged, self).save(*args, **kwargs)
Exemplo n.º 10
0
    def save(self, *args, **kwargs):
        if hasattr(self, "get_absolute_url"):
            model = self.__class__
            if self.pk is not None:
                old_object = model.objects.get(pk=self.pk)
                if old_object.slug != self.slug:
                    redirect = Redirect(
                        site=self.site, old_path=old_object.get_absolute_url(), new_path=self.get_absolute_url()
                    )
                    redirect.save()

        super(Slugged, self).save(*args, **kwargs)
def create_job_redirect(job):
    if not job.unique_slug:
        job.generate_slug()

    for url in [
            "job_view",
            "thumbnail_view",
            "applied_users_details",
            "get_job_applications",
            "job_application_challenge_submission",
    ]:

        redirect = Redirect(
            site_id=settings.SITE_ID,
            old_path=reverse(url, kwargs={"unique_slug": job.pk}),
            new_path=reverse(url, kwargs={"unique_slug": job.unique_slug}),
        )

        redirect.save()
Exemplo n.º 12
0
    def pre_save(self, instance, add):

        # get currently entered slug
        value = self.value_from_object(instance)

        manager = self.manager

        # autopopulate
        if self.always_update or (self.populate_from and not value):
            value = utils.get_prepopulated_value(self, instance)

            if __debug__ and not value:
                print 'Failed to populate slug %s.%s from %s' % \
                    (instance._meta.object_name, self.name, self.populate_from)

        slug = self.slugify(value)

        if not slug:
            # no incoming value,  use model name
            slug = instance._meta.module_name

        assert slug, 'slug is defined before trying to ensure uniqueness'

        slug = utils.crop_slug(self, slug)

        # ensure the slug is unique (if required)
        if self.unique or self.unique_with:
            slug = utils.generate_unique_slug(self, instance, slug, manager)

        assert slug, 'value is filled before saving'

        # check if redirect tracking is on and if so prepare
        if not add and self.redirect_tracking:

            # Can we import the needed django.contrib.redirects app
            try:
                from django.contrib.redirects.models import Redirect
                from django.contrib.sites.models import Site

            except ImportError:
                raise Exception("You are using redirect_tracking. Please be sure to add django contrib apps Redirect and Site to your INSTALLED_APPS.")

            # does model instance have get_absolute_url defined
            try:
                # capture current get_absolute_url
                pre_update_absolute_url = instance.get_absolute_url()

            except AttributeError:
                raise Exception("You are using redirect_tracking on a field whose model does not have get_absolute_url defined. You must define this method on your model.")

        # make the updated slug available as instance attribute
        setattr(instance, self.name, slug)

        if not add and self.redirect_tracking:
            # check if the slug update caused a change in get_absolute_url
            # if so and redirect_tracking = True, record in the django contrib redirect app.
            post_update_absolute_url = instance.get_absolute_url()

            if pre_update_absolute_url != post_update_absolute_url:
                # current site
                site = Site.objects.get_current()

                # add a redirect
                redirect = Redirect(
                    site=site,
                    old_path=pre_update_absolute_url,
                    new_path=post_update_absolute_url
                )
                redirect.save()

        return slug
Exemplo n.º 13
0
def _create_redirects(site, rows):
    for row in rows:
        old_path = row["from"]
        new_path = row["to"]
        redirect = Redirect(site=site, old_path=old_path, new_path=new_path)
        redirect.save()