Example #1
0
    def handle(self, *args, **options):
        if options['truncate']:
            print 'Deleting Blog Entries:'
            for entry in BlogPost.objects.all():
                print '\t{}'.format(entry.title)
            BlogPost.objects.all().delete()

        category_lookup = {}

        with open('db_export/blog_category.csv', 'rb') as f:
            reader = DictReader(f)
            for row in reader:
                category_lookup[row['id']] = BlogCategory.objects.get(title=row['name']).id

        site_id = current_site_id()
        user = User.objects.get(id=1)
        publish_lookup = {'t': 2, 'f': 1}

        with open('db_export/blog_entry.csv', 'rb') as f:
            reader = DictReader(f)
            for row in reader:
                post = BlogPost.objects.create(
                    user=user,
                    site_id=site_id, 
                    title=row['title'],
                    slug=slugify(unicode(row['slug'])),
                    allow_comments=False,
                    content=row['body'],
                    in_sitemap=False,
                    status=publish_lookup[row['published']],
                    publish_date=parse_datetime(row['pub_date'])
                )
                post.categories=[category_lookup[row['category_id']]]
                post.save()
Example #2
0
    def get_queryset(self, request):
        version_tracker_model = self.get_site().get_version_tracker_model()
        site_pages = version_tracker_model.objects.filter(
            widgypage__site_id=current_site_id())
        site_nodes = Node.objects.filter(versiontracker__in=site_pages)

        # This query seems like it could get slow. If that's the case,
        # something along these lines might be helpful:
        # Node.objects.all().extra(
        #     tables=[
        #         '"widgy_node" AS "root"',
        #         'widgy_versiontracker',
        #         'widgy_mezzanine_widgypage',
        #         'pages_page',
        #     ],
        #     where=[
        #         'root.path = SUBSTR(widgy_node.path, 1, 4)',
        #         'widgy_versiontracker.id = widgy_mezzanine_widgypage.root_node_id',
        #         'pages_page.id = widgy_mezzanine_widgypage.page_ptr_id',
        #         'pages_page.site_id = 1',
        #     ]
        # )
        qs = super(MultiSiteFormAdmin, self).get_queryset(request).filter(
            _nodes__path__path_root__in=site_nodes.values_list('path'), )
        return qs
 def choices_for_request(self):
     user = HelpdeskUser.objects.get(pk=self.request.user.pk)
     if user.is_requester():
         self.choices = self.choices.filter(requester=user)
     if user.is_operator():
         self.choices = self.choices.filter(site__id=current_site_id())
     return super(TicketAutocomplete, self).choices_for_request()
Example #4
0
def list_all(request):
    # Find all Newsletters of the current site
    site_id = current_site_id()
    if request.user.is_active and request.user.is_staff:
        letters = models.Newsletter.objects.filter(site__id__exact=site_id)
        letters = models.NewsletterToList.objects.order_by('-date').values(
            'target_list__name', 'newsletter_id', 'newsletter__subject',
            'date').filter(newsletter__in=letters)
    else:
        yearago = datetime.now() - timedelta(days=365)
        letters = models.Newsletter.objects.filter(site__id__exact=site_id)
        letters = models.NewsletterToList.objects.filter(
            target_list__janeus_groups_required='',
            newsletter__public=True,
            date__gt=yearago).order_by('-date').values(
                'target_list__name', 'newsletter_id', 'newsletter__subject',
                'date').filter(newsletter__in=letters)
    letters = [{
        'id':
        s['newsletter_id'],
        'subject':
        '[{}] {}'.format(s['target_list__name'], s['newsletter__subject']),
        'date':
        s['date']
    } for s in letters]
    return render(request, 'hemres/list.html', {'letters': letters})
Example #5
0
    def handle_noargs(self, **options):

        if "conf_setting" not in connection.introspection.table_names():
            createdb.Command.execute(**{'no_data': True})

        for group_name, permission_codenames in [HELPDESK_REQUESTERS,
                                                 HELPDESK_OPERATORS,
                                                 HELPDESK_ADMINS]:
            group, created = Group.objects.get_or_create(name=group_name)
            self.stdout.write('Group {} {}.\n'.format(
                group.name, 'created' if created else 'already exist'))

            for permission in permission_codenames:
                group.permissions.add(Permission.objects.get(
                    content_type__app_label=permission.split('.')[0],
                    codename=permission.split('.')[1]))
            self.stdout.write('Add permissions to {}: {}.\n\n'.format(
                group.name, permission_codenames))

        site = Site.objects.get(pk=current_site_id())
        for code, title, icon in DEFAULT_SOURCES:
            source, created = Source.objects.get_or_create(
                code=code, defaults={'title': title, 'icon': icon})
            if created:
                source.sites.add(site)
Example #6
0
def host_theme_media_path(suffix):  # (instance, filename):
    """
    Returns the name of the theme associated with the given host,
      suffixed by a string (typically a field name) - called by
      upload_to in model.

    Patterned after mezzanine.utils.sites.host_theme_path

    Does not follow the specs here:
    https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.FileField.upload_to
    as Mezzanine has apparently broken this, by mapping upload_to into FileBrowseField.directory,
    which is called without parms.

    Solution:  Use function references with a 'suffix' attr, for example:

    from apps.utils import host_theme_media_path
    ...
    slider_path = host_theme_media_path
    slider_path.suffix = 'slider'
    ...
    class Slide (Orderable):
    ...
        image = FileField (
            verbose_name =_("Image"),
            upload_to = slider_path,  # NOTE: no parens!
            format = "Image", max_length = 255, null = True, blank = True)

    UPDATE: attrs don't work, and it uses the last one set at module load time, the fn references are not first-class objects, only refs.

    Just use a one-line call in the model, and pass is a suffix, eg:

    def slider_path(): return host_theme_media_path ('slider')

    QED. KISS principle.
    """

    # Nope.  need to use attr
    #print 'FUNCTION NAME', host_theme_media_path.__name__

    #suffix = instance.__class__.__name__.tolower()
    #suffix = host_theme_media_path.__name__.split ('_') [-1]
    #suffix = host_theme_media_path.suffix
    if trace: print 'SUFFIX', suffix

    # Set domain to None, which we'll then query for in the first
    # iteration of HOST_THEMES. We use the current site_id rather
    # than a request object here, as it may differ for admin users.
    domain = None

    for (host, theme) in settings.HOST_THEMES:
        if trace: print 'HOST THEME', host, theme
        if domain is None:
            domain = Site.objects.get(id=current_site_id()).domain
            if trace: print 'DOMAIN', domain
        if host.lower() == domain.lower():
            if theme:
                if theme.startswith('apps.'):
                    theme = theme[5:]
                return os.path.join(theme, suffix)  #, filename)
    return ""
Example #7
0
 def _can_edit_content(self, request, obj):
     if isinstance(obj, Content):
         owners = obj.get_root().node.versiontracker_set.get().owners
         any_owner_in_current_site = any(current_site_id() == o.site_id for o in owners)
         return has_site_permission(request.user) and any_owner_in_current_site
     else:
         return True
def get_directory():
    """
    Returns FB's ``DIRECTORY`` setting, appending a directory using
    the site's ID if ``MEDIA_LIBRARY_PER_SITE`` is ``True``, and also
    creating the root directory if missing.
    """
    from mezzanine.conf import settings as mezz_settings
    from mezzanine.utils.sites import current_site_id
    from mezzanine.core.request import current_request
    #from mezzanine.utils.models import get_user_model_name
    dirname = DIRECTORY
    if getattr(mezz_settings, "MEDIA_LIBRARY_PER_SITE", False):
        dirname = os.path.join(dirname, "site-%s" % current_site_id())
    request = current_request()
    username = request.user.username
    if(username=='admin'):
        fullpath = os.path.join(mezz_settings.MEDIA_ROOT, dirname)
        if not default_storage.isdir(fullpath):
            default_storage.makedirs(fullpath)
    else:
        dirname = os.path.join(dirname, "username-%s" % username)
        fullpath = os.path.join(mezz_settings.MEDIA_ROOT, dirname)
        if not default_storage.isdir(fullpath):
            default_storage.makedirs(fullpath)
    return dirname
Example #9
0
def host_theme_media_path (suffix):  # (instance, filename):
    """
    Returns the name of the theme associated with the given host,
      suffixed by a string (typically a field name) - called by
      upload_to in model.

    Patterned after mezzanine.utils.sites.host_theme_path

    Does not follow the specs here:
    https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.FileField.upload_to
    as Mezzanine has apparently broken this, by mapping upload_to into FileBrowseField.directory,
    which is called without parms.

    Solution:  Use function references with a 'suffix' attr, for example:

    from apps.utils import host_theme_media_path
    ...
    slider_path = host_theme_media_path
    slider_path.suffix = 'slider'
    ...
    class Slide (Orderable):
    ...
        image = FileField (
            verbose_name =_("Image"),
            upload_to = slider_path,  # NOTE: no parens!
            format = "Image", max_length = 255, null = True, blank = True)

    UPDATE: attrs don't work, and it uses the last one set at module load time, the fn references are not first-class objects, only refs.

    Just use a one-line call in the model, and pass is a suffix, eg:

    def slider_path(): return host_theme_media_path ('slider')

    QED. KISS principle.
    """

    # Nope.  need to use attr
    #print 'FUNCTION NAME', host_theme_media_path.__name__

    #suffix = instance.__class__.__name__.tolower()
    #suffix = host_theme_media_path.__name__.split ('_') [-1]
    #suffix = host_theme_media_path.suffix
    if trace: print 'SUFFIX', suffix

    # Set domain to None, which we'll then query for in the first
    # iteration of HOST_THEMES. We use the current site_id rather
    # than a request object here, as it may differ for admin users.
    domain = None

    for (host, theme) in settings.HOST_THEMES:
        if trace: print 'HOST THEME', host, theme
        if domain is None:
            domain = Site.objects.get(id=current_site_id()).domain
            if trace: print 'DOMAIN', domain
        if host.lower() == domain.lower():
            if theme:
                if theme.startswith ('apps.'):
                    theme = theme [5:]
                return os.path.join (theme, suffix)  #, filename)
    return ""
Example #10
0
    def __init__(self, *args, **kwargs):
        super(TicketAdminForm, self).__init__(*args, **kwargs)
        # tipologies is filtered by current site if 'tipologies' in
        # self.fields. If field is read_only isn't in self.fields
        # for field, related_name in ('t')
        if "content" in self.fields:
            self.fields["content"].required = True
            self.fields["content"].widget.attrs["class"] = "mceEditor"
        if "source" in self.fields:
            self.fields["source"].required = True
            try:
                self.fields["source"].initial = Source.get_default_obj()
            except Source.DoesNotExist:
                pass
        if not self.instance.pk:
            site = Site.objects.get(pk=current_site_id())
            for field, related_name in [("tipologies", "helpdesk_tipologies"), ("source", "helpdesk_sources")]:
                if field in self.fields:
                    relate_manager = getattr(site, related_name, None)
                    if relate_manager:
                        self.fields[field].queryset = relate_manager.all()

        # The next code is tricky for ensure compatibility with django 1.5
        if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] < 6:  # django 1.5
            if self.instance.pk:  # change form
                for field in ["tipologies", "priority", "content"]:
                    del self.fields[field]
            if len(args) > 0:  # the form is bound
                form_data = args[0]
                for field in self._ohp_only_operators_fields:
                    # if current field is not in buond data whereas is in
                    # self.fields therefore user is an "requester". We then
                    # remove field from form fields (self.fields)
                    if field not in form_data and field in self.fields:
                        del self.fields[field]
Example #11
0
 def __init__(self, *args, **kwargs):
     super(TicketAdminForm, self).__init__(*args, **kwargs)
     # tipologies is filtered by current site if 'tipologies' in
     # self.fields. If field is read_only isn't in self.fields
     # for field, related_name in ('t')
     if 'content' in self.fields:
         self.fields['content'].required = True
         self.fields['content'].widget.attrs['class'] = 'mceEditor'
     if 'source' in self.fields:
         self.fields['source'].required = True
         try:
             self.fields['source'].initial = models.Source.get_default_obj()
         except models.Source.DoesNotExist:
             pass
     if not self.instance.pk:
         site = Site.objects.get(pk=current_site_id())
         for field, related_name in [('tipologies', 'helpdesk_tipologies'),
                                     ('source', 'helpdesk_sources')]:
             if field in self.fields:
                 relate_manager = getattr(site, related_name, None)
                 if relate_manager:
                     if ('initial' in kwargs and
                             field == 'tipologies' and
                             '__tipology_pks' in kwargs['initial']):
                         tipology_pks = kwargs['initial']['__tipology_pks']
                         self.fields[field].queryset = (
                             relate_manager.filter(pk__in=tipology_pks))
                     else:
                         self.fields[field].queryset = relate_manager.all()
Example #12
0
 def __init__(self, *args, **kwargs):
     super(TicketAdminForm, self).__init__(*args, **kwargs)
     # tipologies is filtered by current site if 'tipologies' in
     # self.fields. If field is read_only isn't in self.fields
     # for field, related_name in ('t')
     if 'content' in self.fields:
         self.fields['content'].required = True
         self.fields['content'].widget.attrs['class'] = 'mceEditor'
     if 'source' in self.fields:
         self.fields['source'].required = True
         try:
             self.fields['source'].initial = models.Source.get_default_obj()
         except models.Source.DoesNotExist:
             pass
     if not self.instance.pk:
         site = Site.objects.get(pk=current_site_id())
         for field, related_name in [('tipologies', 'helpdesk_tipologies'),
                                     ('source', 'helpdesk_sources')]:
             if field in self.fields:
                 relate_manager = getattr(site, related_name, None)
                 if relate_manager:
                     if ('initial' in kwargs and field == 'tipologies'
                             and '__tipology_pks' in kwargs['initial']):
                         tipology_pks = kwargs['initial']['__tipology_pks']
                         self.fields[field].queryset = (
                             relate_manager.filter(pk__in=tipology_pks))
                     else:
                         self.fields[field].queryset = relate_manager.all()
Example #13
0
    def get_queryset(self, request):
        version_tracker_model = self.get_site().get_version_tracker_model()
        site_pages = version_tracker_model.objects.filter(widgypage__site_id=current_site_id())
        site_nodes = Node.objects.filter(versiontracker__in=site_pages)

        # This query seems like it could get slow. If that's the case,
        # something along these lines might be helpful:
        # Node.objects.all().extra(
        #     tables=[
        #         '"widgy_node" AS "root"',
        #         'widgy_versiontracker',
        #         'widgy_mezzanine_widgypage',
        #         'pages_page',
        #     ],
        #     where=[
        #         'root.path = SUBSTR(widgy_node.path, 1, 4)',
        #         'widgy_versiontracker.id = widgy_mezzanine_widgypage.root_node_id',
        #         'pages_page.id = widgy_mezzanine_widgypage.page_ptr_id',
        #         'pages_page.site_id = 1',
        #     ]
        # )
        qs = super(MultiSiteFormAdmin, self).get_queryset(request).filter(
            _nodes__path__path_root__in=site_nodes.values_list('path'),
        )
        return qs
Example #14
0
 def choices_for_request(self):
     # user = HelpdeskUser(.objects.get(pk=self.request.user.pk)
     hu = HelpdeskUser(self.request)
     if hu.is_requester():
         self.choices = self.choices.filter(requester=hu.user)
     if hu.is_operator():
         self.choices = self.choices.filter(site__id=current_site_id())
     return super(TicketAutocomplete, self).choices_for_request()
Example #15
0
 def save_form(self, request, form, change):
     """
     Assigns the current site to the redirect when first created.
     """
     obj = form.save(commit=False)
     if not obj.site_id:
         obj.site_id = current_site_id()
     return super(SiteRedirectAdmin, self).save_form(request, form, change)
Example #16
0
def admin_dropdown_menu(context):
    """
    Renders the app list for the admin dropdown menu navigation.
    """
    context["dropdown_menu_app_list"] = admin_app_list(context["request"])
    context["dropdown_menu_sites"] = list(Site.objects.all())
    context["dropdown_menu_selected_site_id"] = current_site_id()
    return context
Example #17
0
 def save_form(self, request, form, change):
     """
     Assigns the current site to the redirect when first created.
     """
     obj = form.save(commit=False)
     if not obj.site_id:
         obj.site_id = current_site_id()
     return super(SiteRedirectAdmin, self).save_form(request, form, change)
Example #18
0
def admin_dropdown_menu(context):
    """
    Renders the app list for the admin dropdown menu navigation.
    """
    context["dropdown_menu_app_list"] = admin_app_list(context["request"])
    context["dropdown_menu_sites"] = list(Site.objects.all())
    context["dropdown_menu_selected_site_id"] = current_site_id()
    return context
Example #19
0
 def _can_edit_content(self, request, obj):
     if isinstance(obj, Content):
         owners = obj.get_root().node.versiontracker_set.get().owners
         any_owner_in_current_site = any(current_site_id() == o.site_id
                                         for o in owners)
         return has_site_permission(
             request.user) and any_owner_in_current_site
     else:
         return True
Example #20
0
 def get_query_set(self):
     if not self.__is_validated:
         try:
             # Django <= 1.6
             self._validate_field_name()
         except AttributeError:
             pass
     lookup = {self.__field_name + "__id__exact": current_site_id()}
     return super(DjangoCSM, self).get_query_set().filter(**lookup)
Example #21
0
    def save_form(self, request, form, change):
        # we only want to intercept for adding
        if change:
            return super(NewsletterAdmin, self).save_form(request, form, True)

        # get the information from the form
        template = form.cleaned_data['template']
        subject = form.cleaned_data['subject']
        newsletter = template.create_newsletter(subject=subject)

        # now write the newsletter using some hard-coded (ew) template
        newsletter.content = "<h1>Beste {{naam}},</h1>"
        newsletter.content += "<p>Introductietekst</p>"

        # if we want events, add each event (again, hard-coded)
        if len(form.cleaned_data['events']):
            newsletter.content += "<h2 id='agenda'>Agenda</h2>"
        current_site = current_site_id()
        for o in form.cleaned_data['events']:
            start = timezone.localtime(o.start_time)
            end = timezone.localtime(o.end_time)
            duration = start.strftime('%A, %d %B %Y %H:%M')

            if (start.day == end.day and start.month == end.month
                    and start.year == end.year):
                duration += ' - {:%H:%M}'.format(end)
            else:
                duration += ' - {:%A, %d %B %Y %H:%M}'.format(end)

            # for URLs to the site, look if we have SSL_ENABLED and choose https if so
            protocol = "http"
            try:
                from mezzanine.conf import settings as msettings
                if msettings.SSL_ENABLED:
                    protocol = "https"
            except:
                pass

            if o.event.site.id != current_site:
                tag = "<strong>[{}]</strong> ".format(o.event.site.name)
            else:
                tag = ""

            newsletter.content += '<h3 class="agendaitem">{}<a href="{}://{}{}">{}</a></h3>'.format(
                tag, protocol, o.event.site.domain, o.get_absolute_url(),
                o.title)
            newsletter.content += "<p>"
            newsletter.content += "<strong>Wanneer</strong>: {}<br/>".format(
                duration)
            newsletter.content += "<strong>Waar</strong>: {}<br/>".format(
                o.location)
            newsletter.content += "{}".format(o.event.description)
            newsletter.content += "</p>"

        # all events added, save and return!
        newsletter.save()
        return newsletter
Example #22
0
def get_tipologies(n_tipologies):
    from django.contrib.sites.models import Site
    from .factories import CategoryFactory, TipologyFactory
    from mezzanine.utils.sites import current_site_id
    category = CategoryFactory()
    site = Site.objects.get(pk=current_site_id())
    return [
        TipologyFactory(sites=(site,), category=category)
        for i in range(0, n_tipologies)]
Example #23
0
 def insert_trans_page(self):
     # Ignore gen_description field
     # It causes the description field to not be encoded to unicode
     if 'gen_description' in self.page_json:
         self.page_json['gen_description'] = False
     if type(self.page_content_model.__base__) != type(Page):
         self.page_json['site_id'] = current_site_id()
     self.page = self.page_content_model(**self.page_json)
     self.page.save()
Example #24
0
 def get_query_set(self):
     if not self.__is_validated:
         try:
             # Django <= 1.6
             self._validate_field_name()
         except AttributeError:
             pass
     lookup = {self.__field_name + "__id__exact": current_site_id()}
     return super(DjangoCSM, self).get_query_set().filter(**lookup)
Example #25
0
def get_tipologies(n_tipologies):
    from django.contrib.sites.models import Site
    from .factories import CategoryFactory, TipologyFactory
    from mezzanine.utils.sites import current_site_id
    category = CategoryFactory()
    site = Site.objects.get(pk=current_site_id())
    return [
        TipologyFactory(sites=(site,), category=category)
        for i in range(0, n_tipologies)]
Example #26
0
 def insert_trans_page(self):
     # Ignore gen_description field
     # It causes the description field to not be encoded to unicode
     if 'gen_description' in self.page_json:
         self.page_json['gen_description'] = False
     if type(self.page_content_model.__base__) != type(Page):
         self.page_json['site_id'] = current_site_id()
     self.page = self.page_content_model(**self.page_json)
     self.page.save()
Example #27
0
def create_site_permission(sender, **kw):
    sender_name = "%s.%s" % (sender._meta.app_label, sender._meta.object_name)
    if sender_name.lower() != user_model_name.lower():
        return
    user = kw["instance"]
    if user.is_staff and not user.is_superuser:
        perm, created = SitePermission.objects.get_or_create(user=user)
        if created or perm.sites.count() < 1:
            perm.sites.add(current_site_id())
Example #28
0
 def save(self, update_site=False, *args, **kwargs):
     """
     Set the site to the current site when the record is first
     created, or the ``update_site`` argument is explicitly set
     to ``True``.
     """
     if update_site or not self.id:
         self.site_id = current_site_id()
     super(SiteRelated, self).save(*args, **kwargs)
Example #29
0
 def save(self, update_site=False, *args, **kwargs):
     """
     Set the site to the current site when the record is first
     created, or the ``update_site`` argument is explicitly set
     to ``True``.
     """
     if update_site or (self.id is None and self.site_id is None):
         self.site_id = current_site_id()
     super(SiteRelated, self).save(*args, **kwargs)
Example #30
0
def create_site_permission(sender, **kw):
    sender_name = "%s.%s" % (sender._meta.app_label, sender._meta.object_name)
    if sender_name.lower() != user_model_name.lower():
        return
    user = kw["instance"]
    if user.is_staff and not user.is_superuser:
        perm, created = SitePermission.objects.get_or_create(user=user)
        if created or perm.sites.count() < 1:
            perm.sites.add(current_site_id())
Example #31
0
 def save(self, *args, **kwargs):
     """
     Set the current site ID, and ``is_public`` based on the setting
     ``COMMENTS_DEFAULT_APPROVED``.
     """
     if not self.id:
         self.is_public = settings.COMMENTS_DEFAULT_APPROVED
         self.site_id = current_site_id()
     super(ThreadedComment, self).save(*args, **kwargs)
Example #32
0
 def save(self, *args, **kwargs):
     """
     Set the current site ID, and ``is_public`` based on the setting
     ``COMMENTS_DEFAULT_APPROVED``.
     """
     if not self.id:
         self.is_public = settings.COMMENTS_DEFAULT_APPROVED
         self.site_id = current_site_id()
     super(ThreadedComment, self).save(*args, **kwargs)
Example #33
0
def cache_key_prefix(request):
    """
    Cache key for Mezzanine's cache middleware. Adds the current
    device and site ID.
    """
    return "%s.%s.%s." % (
        settings.CACHE_MIDDLEWARE_KEY_PREFIX,
        current_site_id(),
        device_from_request(request) or "default",
    )
Example #34
0
 def get_or_create_user(self, username, ldap_user):
     user, create = super(MezzanineLDAPBackend, self).get_or_create_user(
         username, ldap_user)
     if create:
         sp, _ = SitePermission.objects.get_or_create(user=user)
         try:
             sp.sites.add(Site.objects.get(pk=current_site_id()))
         except Site.DoesNotExist:
             pass
     return user, create
Example #35
0
 def upsert_relational_objects(self):
     for related_obj_name in self.related_object_names:
         if related_obj_name == 'page_type':
             continue
         related_obj_model = get_content_model(related_obj_name)
         # Is it a m2m object?
         m2m_field_names = self.many_to_many_field_names(related_obj_model)
         if len(m2m_field_names) > 0:
             for m2m_fldname in m2m_field_names:
                 for m2m_json_obj in self.smrt_json[related_obj_name]:
                     # Attempt to find m2m object that exists
                     if 'id' in m2m_json_obj:
                         del m2m_json_obj['id']
                     m2m_obj = self.find_many_to_many_object(m2m_json_obj, related_obj_model)
                     if not m2m_obj:
                         site = Site.objects.get(id=current_site_id())
                         try:
                             m2m_json_obj['site'] = site
                             m2m_obj = related_obj_model(**m2m_json_obj)
                             m2m_obj.save()
                             del m2m_json_obj['site']
                         except TypeError:
                             del m2m_json_obj['site']
                             m2m_obj = related_obj_model(**m2m_json_obj)
                             m2m_obj.save()
                     getattr(self.page, m2m_fldname).add(m2m_obj)
         else:
             foreign_key_field = self.get_foreign_key_field(related_obj_model)
             for foreign_json_object in self.smrt_json[related_obj_name]:
                 foreign_json_object[foreign_key_field] = self.page
                 self.upsert_follow_objects(foreign_json_object, related_obj_model)
                 try:
                     foreign_json_object['site'] = current_site_id()
                     fk_obj = related_obj_model(**foreign_json_object)
                     fk_obj.save()
                 except TypeError:
                     del foreign_json_object['site']
                     fk_obj = related_obj_model(**foreign_json_object)
                     fk_obj.save()
                 if foreign_key_field in foreign_json_object:
                     del foreign_json_object[foreign_key_field]
                 self.remove_related_follow_fields(foreign_json_object, related_obj_model)
Example #36
0
 def upsert_relational_objects(self):
     for related_obj_name in self.related_object_names:
         if related_obj_name == 'page_type':
             continue
         related_obj_model = get_content_model(related_obj_name)
         # Is it a m2m object?
         m2m_field_names = self.many_to_many_field_names(related_obj_model)
         if len(m2m_field_names) > 0:
             for m2m_fldname in m2m_field_names:
                 for m2m_json_obj in self.smrt_json[related_obj_name]:
                     # Attempt to find m2m object that exists
                     if 'id' in m2m_json_obj:
                         del m2m_json_obj['id']
                     m2m_obj = self.find_many_to_many_object(m2m_json_obj, related_obj_model)
                     if not m2m_obj:
                         site = Site.objects.get(id=current_site_id())
                         try:
                             m2m_json_obj['site'] = site
                             m2m_obj = related_obj_model(**m2m_json_obj)
                             m2m_obj.save()
                             del m2m_json_obj['site']
                         except TypeError:
                             del m2m_json_obj['site']
                             m2m_obj = related_obj_model(**m2m_json_obj)
                             m2m_obj.save()
                     getattr(self.page, m2m_fldname).add(m2m_obj)
         else:
             foreign_key_field = self.get_foreign_key_field(related_obj_model)
             for foreign_json_object in self.smrt_json[related_obj_name]:
                 foreign_json_object[foreign_key_field] = self.page
                 self.upsert_follow_objects(foreign_json_object, related_obj_model)
                 try:
                     foreign_json_object['site'] = current_site_id()
                     fk_obj = related_obj_model(**foreign_json_object)
                     fk_obj.save()
                 except TypeError:
                     del foreign_json_object['site']
                     fk_obj = related_obj_model(**foreign_json_object)
                     fk_obj.save()
                 if foreign_key_field in foreign_json_object:
                     del foreign_json_object[foreign_key_field]
                 self.remove_related_follow_fields(foreign_json_object, related_obj_model)
Example #37
0
def cache_key_prefix(request):
    """
    Cache key for Mezzanine's cache middleware. Adds the current
    device and site ID.
    """
    cache_key = "%s.%s.%s." % (
        settings.CACHE_MIDDLEWARE_KEY_PREFIX,
        current_site_id(),
        device_from_request(request) or "default",
    )
    return _i18n_cache_key_suffix(request, cache_key)
def add_site_permission(user, site=None):
    """
    Add permissions for a site to the user.
    Without this non-superusers cannot login to the admin.
    The current site will be used if the site kwarg is not provided.
    """
    if not isinstance(site, Site):
        site = Site.objects.get(id=current_site_id())

    siteperm, _ = SitePermission.objects.get_or_create(user=user)
    siteperm.sites.add(site)
    def handle(self, *args, **options):
        if options['truncate']:
            print 'Deleting Gallery Categories:'
            for gallery in Gallery.objects.filter(~Q(title='Gallery')):
                print '\t{}'.format(gallery.title)
            Gallery.objects.filter(~Q(title='Gallery')).delete()

        site_id = current_site_id()
        child_galleries = []

        parent_lookup = {
            '': Gallery.objects.get(title='Gallery').id
        }

        publish_lookup = {'t': 2, 'f': 1}

        with open('db_export/gallery_category.csv', 'rb') as f:
            reader = DictReader(f)
            for row in reader:
                options = {
                    'site_id':site_id,
                    'title':row['name'],
                    'content':row['description'],
                    'in_sitemap':True,
                    'in_menus': '',
                    'status':publish_lookup[row['published']]
                }
                if row['parent_id'] in parent_lookup:
                    options['parent_id'] = parent_lookup[row['parent_id']]
                else:
                    options['parent_id'] = row['parent_id']
                    child_galleries.append(options)
                    continue

                print 'Creating Gallery {}'.format(row['name'])

                g = Gallery.objects.create(**options)
                parent_lookup[row['id']] = g.id

        # recursively add new galleries to parents that didn't exist in N-1 pass
        while len(child_galleries) > 0:
            orphaned = []
            for child in child_galleries:
                if child['parent_id'] in parent_lookup:
                    row_id = child['parent_id']
                    child['parent_id'] = Gallery.objects.get(id=parent_lookup[row_id]).id

                    print 'Creating Gallery {}'.format(child['title'])
                    g = Gallery.objects.create(**child)
                    parent_lookup[row_id] = g.id
                else:
                    orphaned.append(child)

            child_galleries = orphaned
Example #40
0
def admin_dropdown_menu(context):
    """
    Renders the app list for the admin dropdown menu navigation.
    """
    context["dropdown_menu_app_list"] = admin_app_list(context["request"])
    user = context["request"].user
    if user.is_superuser:
        context["dropdown_menu_sites"] = list(Site.objects.all())
    else:
        context["dropdown_menu_sites"] = list(user.sitepermission.sites.all())
    context["dropdown_menu_selected_site_id"] = current_site_id()
    return context
Example #41
0
 def get_icalendar_event(self):
     """
     Builds an icalendar.event object from event data.
     """
     icalendar_event = IEvent()
     icalendar_event.add('summary'.encode("utf-8"), self.title)
     icalendar_event.add('url', 'http://{domain}{url}'.format(
         domain=Site.objects.get(id=current_site_id()).domain,
         url=self.get_absolute_url(),
     ))
     if self.location:
         icalendar_event.add('location'.encode("utf-8"), self.location.address)
     icalendar_event.add('dtstamp', self.start)
     icalendar_event.add('dtstart', self.start)
     if self.end:
         icalendar_event.add('dtend', self.end)
     icalendar_event['uid'.encode("utf-8")] = "event-{id}@{domain}".format(
         id=self.id,
         domain=Site.objects.get(id=current_site_id()).domain,
     ).encode("utf-8")
     return icalendar_event
Example #42
0
def admin_dropdown_menu(context):
    """
    Renders the app list for the admin dropdown menu navigation.
    """
    context["dropdown_menu_app_list"] = admin_app_list(context["request"])
    user = context["request"].user
    if user.is_superuser:
        context["dropdown_menu_sites"] = list(Site.objects.all())
    else:
        context["dropdown_menu_sites"] = list(user.sitepermission.sites.all())
    context["dropdown_menu_selected_site_id"] = current_site_id()
    return context
Example #43
0
 def save(self, update_site=False, *args, **kwargs):
     """
     Set the site to the current site when the record is first
     created, or the ``update_site`` argument is explicitly set
     to ``True``.
     """
     if update_site or not self.id:
         self.site_id = current_site_id()
         curr_site = Site.objects.filter(id=self.site_id)
         if curr_site.exists():
             self.sites.add(curr_site[0])
     super(SiteRelated, self).save(*args, **kwargs)
Example #44
0
def get_directory():
    """
    Returns FB's ``DIRECTORY`` setting, appending a directory using
    the site's ID if ``MEDIA_LIBRARY_PER_SITE`` is ``True``, and also
    creating the root directory if missing.
    """
    dirname = DIRECTORY
    if getattr(mezz_settings, "MEDIA_LIBRARY_PER_SITE", False):
        dirname = os.path.join(dirname, "site-%s" % current_site_id())
    fullpath = os.path.join(mezz_settings.MEDIA_ROOT, dirname)
    if not default_storage.isdir(fullpath):
        default_storage.makedirs(fullpath)
    return dirname
Example #45
0
def get_sitewide_content():
  """
  Adds the `SitewideContent` to the context
  """
  args = {}
  args['setting']= Site_setting.objects.get_or_create(site_id=current_site_id())[0]
  args['social'] = Social.objects.all()
  args['events'] = Event.objects.all()
  args['cofcs'] = CodeOfConduct.objects.all()
  args['pastwinners'] = PastWinner.objects.all().order_by('-year')


  return args
 def test_email_is_sent_to_operators(self):
     site_conf = SiteConfiguration(
         site=Site.objects.get(pk=current_site_id()))
     site_conf._email_addr_from = '*****@*****.**'
     site_conf._email_addr_to_1 = '*****@*****.**'
     site_conf.save()
     self.form.submit('_save')
     self.assertEqual(len(mail.outbox), 1)
     email = mail.outbox[0]
     """:type : django.core.mail.EmailMessage"""
     self.assertEqual(email.subject,
                      "New ticket created by {}".format(self.user.username))
     self.assertSetEqual(set(email.to), set(site_conf.email_addrs_to))
     self.assertEqual(email.from_email, site_conf.email_addr_from)
 def test_email_is_sent_to_operators(self):
     site_conf = SiteConfiguration(
         site=Site.objects.get(pk=current_site_id()))
     site_conf._email_addr_from = '*****@*****.**'
     site_conf._email_addr_to_1 = '*****@*****.**'
     site_conf.save()
     self.form.submit('_save')
     self.assertEqual(len(mail.outbox), 1)
     email = mail.outbox[0]
     """:type : django.core.mail.EmailMessage"""
     self.assertEqual(email.subject,
                      "New ticket created by {}".format(self.user.username))
     self.assertSetEqual(set(email.to), set(site_conf.email_addrs_to))
     self.assertEqual(email.from_email, site_conf.email_addr_from)
Example #48
0
def get_directory():
    """
    Returns FB's ``DIRECTORY`` setting, appending a directory using
    the site's ID if ``MEDIA_LIBRARY_PER_SITE`` is ``True``, and also
    creating the root directory if missing.
    """

    dirname = fb_settings.DIRECTORY
    if getattr(dj_settings, "MEDIA_LIBRARY_PER_SITE", False):
        dirname = os.path.join(dirname, "site-%s" % current_site_id())
    fullpath = os.path.join(dj_settings.MEDIA_ROOT, dirname)
    if not default_storage.isdir(fullpath):
        default_storage.makedirs(fullpath)
    return dirname
Example #49
0
    def create_event(self, data, data_url, user):
        """
        Create an Event instance based on serialized data.
        The featured image will be retrieved from the original server
        and the EventDateTime instances will be attached.
        """
        converted = convert(data)
        items = deserialize("json", json.dumps([converted]), ignorenonexistent=True)
        event = list(items)[0].object
        event.id = None  # Ensure new event ID
        event.slug = event.generate_unique_slug()
        event.site_id = current_site_id()
        event.user = user

        if not event.location:
            event.location = data["fields"].get("location_title", "")

        # Get the original featured image and save it locally
        img_path = data["fields"].get("featured_image")
        if img_path:
            parts = urlparse(data_url)
            img_url = urljoin(parts.scheme + "://" + parts.hostname, "static/media/" + img_path)
            img_response = requests.get(img_url)
            if img_response.status_code == requests.codes.ok:
                _, filename = os.path.split(img_path)
                filepath = os.path.join("uploads", "events", unquote(filename))
                filepath = default_storage.save(filepath, ContentFile(img_response.content))
                event.featured_image = filepath

        # Discard all M2M data as it may cause integrity issues when saving
        event.m2m_data = {}
        # Commit the new event to the database (required before saving EventDateTimes)
        event.save()

        # Add EventDateTimes instances (for old Mezzanine Calendar objects)
        for dt in data.get("dateandtimes", []):
            dt = convert(dt)
            occ = deserialize("json", json.dumps([dt]), ignorenonexistent=True)
            occ = list(occ)[0].object
            occ.event = event
            occ.save()

        # Import occurrences (if available)
        for occ_data in data.get("occurrences", []):
            occ = occ_data["fields"].copy()
            occ.pop("event")
            event.occurrences.create(**occ)

        return event
Example #50
0
def cache_key_prefix(request):
    """
    Cache key for Mezzanine's cache middleware. Adds the current
    site ID.
    """
    cache_key = "%s.%s.%s" % (
        settings.CACHE_MIDDLEWARE_KEY_PREFIX,
        current_site_id(),
        # This last part used to indicate the device type for the request,
        # but device detection was removed in Mezzanine 4.3.
        # The "default" value was kept to maintain existing cache keys.
        # See: https://github.com/stephenmcd/mezzanine/pull/1783
        "default",
    )
    return _i18n_cache_key_suffix(request, cache_key)
Example #51
0
def cache_key_prefix(request):
    """
    Cache key for Mezzanine's cache middleware. Adds the current
    site ID.
    """
    cache_key = "%s.%s.%s" % (
        settings.CACHE_MIDDLEWARE_KEY_PREFIX,
        current_site_id(),
        # This last part used to indicate the device type for the request,
        # but device detection was removed in Mezzanine 4.3.
        # The "default" value was kept to maintain existing cache keys.
        # See: https://github.com/stephenmcd/mezzanine/pull/1783
        "default",
    )
    return _i18n_cache_key_suffix(request, cache_key)
Example #52
0
 def current_site_id():
     if hasattr(settings, 'JANEUS_CURRENT_SITE'):
         if callable(settings.JANEUS_CURRENT_SITE):
             site = settings.JANEUS_CURRENT_SITE()
         else:
             site = settings.JANEUS_CURRENT_SITE
         return site.id if isinstance(site, Site) else site
     elif apps.is_installed('mezzanine.core'):
         from mezzanine.utils.sites import current_site_id
         return current_site_id()
     else:
         from django.contrib.sites.shortcuts import get_current_site
         from janeus.utils import current_request
         site = get_current_site(current_request())
         return site.id if isinstance(site, Site) else None
Example #53
0
def cache_key_prefix(request, ignore_device=False):
    """
    Cache key for Mezzanine's cache middleware. Adds the current
    device and site ID, unless ignore_device is True in which case
    it will only add the current site ID.
    """
    cache_key = "%s.%s." % (
        settings.CACHE_MIDDLEWARE_KEY_PREFIX,
        current_site_id(),
    )

    if not ignore_device:
        cache_key += (device_from_request(request) or "default") + "."

    return _i18n_cache_key_suffix(request, cache_key)
Example #54
0
def helpdesker(helpdesker_conf):
    import openhelpdesk.defaults
    from tests.factories import UserFactory, GroupFactory
    from mezzanine.utils.sites import current_site_id

    helpdesker_conf = getattr(openhelpdesk.defaults, helpdesker_conf, None)
    if not helpdesker_conf:
        return None
    user = UserFactory(
        username=helpdesker_conf[0].rstrip('s'),
        groups=[GroupFactory(name=helpdesker_conf[0],
                             permissions=list(helpdesker_conf[1]))])
    site_perm, created = user.sitepermissions.get_or_create(user=user)
    if created or site_perm.sites.count() < 1:
        site_perm.sites.add(current_site_id())
    return user
Example #55
0
 def process_response(self, request, response):
     if response.status_code == 404:
         lookup = {
             "site_id": current_site_id(),
             "old_path": request.get_full_path(),
         }
         try:
             redirect = Redirect.objects.get(**lookup)
         except Redirect.DoesNotExist:
             pass
         else:
             if not redirect.new_path:
                 response = HttpResponseGone()
             else:
                 response = HttpResponsePermanentRedirect(redirect.new_path)
     return response
Example #56
0
 def process_response(self, request, response):
     if response.status_code == 404:
         lookup = {
             "site_id": current_site_id(),
             "old_path": request.get_full_path(),
         }
         try:
             redirect = Redirect.objects.get(**lookup)
         except Redirect.DoesNotExist:
             pass
         else:
             if not redirect.new_path:
                 response = HttpResponseGone()
             else:
                 response = HttpResponsePermanentRedirect(redirect.new_path)
     return response
Example #57
0
def admin_dropdown_menu(context):
    """
    Renders the app list for the admin dropdown menu navigation.
    """
    user = context["request"].user
    if user.is_staff:
        context["dropdown_menu_app_list"] = admin_app_list(context["request"])
        if user.is_superuser:
            sites = Site.objects.all()
        else:
            try:
                sites = user.sitepermissions.sites.all()
            except ObjectDoesNotExist:
                sites = Site.objects.none()
        context["dropdown_menu_sites"] = list(sites)
        context["dropdown_menu_selected_site_id"] = current_site_id()
        return context.flatten()