Esempio n. 1
0
def configure_extra_views(app, admin):
    # adding extra views
    extra_views = app.config.get('ADMIN_EXTRA_VIEWS', [])
    for view in extra_views:
        admin.add_view(
            import_string(view['module'])(category=_l(view.get('category')),
                                          name=_l(view.get('name'))))
Esempio n. 2
0
def configure_file_admin(app, admin):
    for entry in app.config.get('FILE_ADMIN', []):
        try:
            admin.add_view(
                FileAdmin(
                    entry['path'],
                    entry['url'],
                    name=_l(entry['name']),
                    category=_l(entry['category']),
                    endpoint=entry['endpoint'],
                    editable_extensions=entry.get('editable_extensions')))
        except Exception as e:
            app.logger.info(e)
Esempio n. 3
0
def load_models():
    if not session.get('cart_loaded_models'):
        session['cart_loaded_models'] = True
        classes = [x.get_class_from_db() for x in ProductType.objects.all()]
        print "loaded models"
        for c in classes:
            admin_class = type('{}Admin'.format(c.__name__), (BaseView, ), {})
            admin.register(c, name=_l(c.__name__), category=_("Cart"))
Esempio n. 4
0
class MediaAdmin(ModelAdmin):
    roles_accepted = ('admin', 'editor', 'author')
    column_list = ('title', 'path', 'published')
    form_columns = ['title', 'slug', 'path', 'channel', 'content_format',
                    'summary', 'comments_enabled', 'published']

    form_overrides = {
        'path': form.FileUploadField
    }

    form_args = {
        'summary': {'widget': TextEditor()},
        'slug': {'widget': PrepopulatedText(master='title')},
    }

    form_widget_args = {
        'channel': {'data-placeholder': _l('media/')}
    }
Esempio n. 5
0
    form_args = {
        "description": {
            "widget": TextEditor()
        },
        "identifier": {
            "widget": PrepopulatedText(master='title')
        }
    }
    form_columns = ('title', 'identifier', 'description', 'module', 'requires',
                    'image', 'link', 'config', 'pipeline', 'published')
    form_ajax_refs = {'image': {'fields': ['title', 'long_slug', 'summary']}}

    form_widget_args = {
        'config': {
            'cols': 40,
            'rows': 10,
            'style': 'width:500px;'
        }
    }


admin.register(Cart, CartAdmin, category=_("Cart"), name=_l("Cart"))
admin.register(Processor,
               ProcessorAdmin,
               category=_("Cart"),
               name=_l("Processor"))
admin.register(TestProduct,
               ProductAdmin,
               category=_("Cart"),
               name=_l("Products"))
Esempio n. 6
0
class Cart(Publishable, db.DynamicDocument):
    STATUS = (
        ("pending", _l("Pending")),  # not checked out
        ("checked_out", _l("Checked out")),  # not confirmed (payment)
        ("analysing", _l("Analysing")),  # Analysing payment
        ("confirmed", _l("Confirmed")),  # Payment confirmed
        ("completed", _l("Completed")),  # Payment completed (money released)
        ("refunding", _l("Refunding")),  # Buyer asks refund
        ("refunded", _l("Refunded")),  # Money refunded to buyer
        ("cancelled", _l("Cancelled")),  # Cancelled without processing
        ("abandoned", _l("Abandoned")),  # Long time no update
    )
    reference = db.GenericReferenceField()
    """reference must implement set_status(**kwargs) method
    arguments: status(str), value(float), date, uid(str), msg(str)
    and extra(dict).
    Also reference must implement get_uid() which will return
    the unique identifier for this transaction"""

    belongs_to = db.ReferenceField(
        'User',
        # default=get_current_user,
        reverse_delete_rule=db.NULLIFY)
    items = db.ListField(db.EmbeddedDocumentField(Item))
    payment = db.ListField(db.EmbeddedDocumentField(Payment))
    status = db.StringField(choices=STATUS, default='pending')
    total = db.FloatField(default=0)
    extra_costs = db.DictField(default=lambda: {})
    sender_data = db.DictField(default=lambda: {})
    shipping_data = db.DictField(default=lambda: {})
    shipping_cost = db.FloatField(default=0)
    tax = db.FloatField(default=0)
    processor = db.ReferenceField(Processor,
                                  default=Processor.get_default_processor,
                                  reverse_delete_rule=db.NULLIFY)
    reference_code = db.StringField()  # Reference code for filtering
    checkout_code = db.StringField()  # The UID for transaction checkout
    transaction_code = db.StringField()  # The UID for transaction
    requires_login = db.BooleanField(default=True)
    continue_shopping_url = db.StringField(
        default=lambda: current_app.config.get('CART_CONTINUE_SHOPPING_URL',
                                               '/'))
    pipeline = db.ListField(db.StringField(), default=[])
    log = db.ListField(db.StringField(), default=[])
    config = db.DictField(default=lambda: {})

    search_helper = db.StringField()

    meta = {'ordering': ['-created_at']}

    def send_response(self, response, identifier):
        if self.reference and hasattr(self.reference, 'get_response'):
            self.reference.get_response(response, identifier)

        for item in self.items:
            if hasattr(item, 'get_response'):
                item.get_response(response, identifier)

    def set_tax(self, tax, save=False):
        """
        set tax and send to references
        """
        try:
            tax = float(tax)
            self.tax = tax
            self.set_reference_tax(tax)
        except Exception as e:
            self.addlog("impossible to set tax: %s" % str(e))

    def set_status(self, status, save=False):
        """
        THis method will be called by the processor
        which will pass a valid status as in STATUS
        so, this method will dispatch the STATUS to
        all the items and also the 'reference' if set
        """
        if self.status != status:
            self.status = status

        self.set_reference_statuses(status)

        if save:
            self.save()

    def set_reference_statuses(self, status):
        if self.reference and hasattr(self.reference, 'set_status'):
            self.reference.set_status(status, cart=self)

        for item in self.items:
            item.set_status(status, cart=self)

    def set_reference_tax(self, tax):
        if self.reference and hasattr(self.reference, 'set_tax'):
            self.reference.set_tax(tax)

        for item in self.items:
            if hasattr(item, 'set_tax'):
                item.set_tax(tax)

    def addlog(self, msg, save=True):
        try:
            self.log.append(u"{0},{1}".format(datetime.datetime.now(), msg))
            logger.debug(msg)
            save and self.save()
        except UnicodeDecodeError as e:
            logger.info(msg)
            logger.error(str(e))

    @property
    def uid(self):
        return self.get_uid()

    def get_uid(self):
        try:
            return self.reference.get_uid() or str(self.id)
        except Exception:
            self.addlog("Using self.id as reference", save=False)
            return str(self.id)

    def __unicode__(self):
        return u"{o.uid} - {o.processor.identifier}".format(o=self)

    def get_extra_costs(self):
        if self.extra_costs:
            return sum(self.extra_costs.values())

    @classmethod
    def get_cart(cls, no_dereference=False, save=True):
        """
        get or create a new cart related to the session
        if there is a current logged in user it will be set
        else it will be set during the checkout.
        """
        session.permanent = current_app.config.get("CART_PERMANENT_SESSION",
                                                   True)
        try:
            cart = cls.objects(id=session.get('cart_id'), status='pending')

            if not cart:
                raise cls.DoesNotExist('A pending cart not found')

            if no_dereference:
                cart = cart.no_dereference()

            cart = cart.first()

            save and cart.save()

        except (cls.DoesNotExist, db.ValidationError):
            cart = cls(status="pending")
            cart.save()
            session['cart_id'] = str(cart.id)
            session.pop('cart_pipeline_index', None)
            session.pop('cart_pipeline_args', None)

        return cart

    def assign(self):
        self.belongs_to = self.belongs_to or get_current_user()

    def save(self, *args, **kwargs):
        self.total = sum([item.total for item in self.items])
        self.assign()
        self.reference_code = self.get_uid()
        self.search_helper = self.get_search_helper()
        if not self.id:
            self.published = True
        super(Cart, self).save(*args, **kwargs)
        self.set_reference_statuses(self.status)

    def get_search_helper(self):
        if not self.belongs_to:
            return ""
        user = self.belongs_to
        return " ".join([user.name or "", user.email or ""])

    def get_item(self, uid):
        # MongoEngine/mongoengine#503
        return self.items.get(uid=uid)

    def set_item(self, **kwargs):
        if 'product' in kwargs:
            if not isinstance(kwargs['product'], Content):
                try:
                    kwargs['product'] = Content.objects.get(
                        id=kwargs['product'])
                except Content.DoesNotExist:
                    kwargs['product'] = None

        uid = kwargs.get(
            'uid',
            kwargs['product'].get_uid() if kwargs.get('product') else None)

        if not uid:
            self.addlog("Cannot add item without an uid %s" % kwargs)
            return

        item = self.get_item(uid)

        kwargs = Item.normalize(kwargs)

        if not item:
            # items should only be added if there is a product (for safety)
            if not kwargs.get('product'):
                self.addlog("there is no product to add item")
                return
            allowed = ['product', 'quantity']
            item = self.items.create(
                **{k: v
                   for k, v in kwargs.items() if k in allowed})
            self.addlog("New item created %s" % item, save=False)
        else:
            # update only allowed attributes
            item = self.items.update(
                {k: v
                 for k, v in kwargs.items() if k in item.allowed_to_set},
                uid=item.uid)
            self.addlog("Item updated %s" % item, save=False)

            if int(kwargs.get('quantity', "1")) == 0:
                self.addlog("quantity is 0, removed %s" % kwargs, save=False)
                self.remove_item(**kwargs)

        self.save()
        self.reload()
        return item

    def remove_item(self, **kwargs):
        deleted = self.items.delete(**kwargs)
        if self.reference and hasattr(self.reference, 'remove_item'):
            self.reference.remove_item(**kwargs)
        return deleted

    def checkout(self, processor=None, *args, **kwargs):
        self.set_processor(processor)
        processor_instance = self.processor.get_instance(self, *args, **kwargs)
        if processor_instance.validate():
            response = processor_instance.process()
            self.status = 'checked_out'
            self.save()
            session.pop('cart_id', None)
            return response
        else:
            self.addlog("Cart did not validate")
            raise Exception("Cart did not validate")  # todo: specialize this

    def get_items_pipeline(self):
        if not self.items:
            return []

        return reduce(lambda x, y: x + y,
                      [item.pipeline for item in self.items])

    def build_pipeline(self):
        items = ['quokka.modules.cart.pipelines:StartPipeline']
        items.extend(current_app.config.get('CART_PIPELINE', []))
        items.extend(self.get_items_pipeline())
        items.extend(self.pipeline)
        items.extend(self.processor and self.processor.pipeline or [])
        return items

    def process_pipeline(self):
        if not self.items:
            return render_template('cart/empty_cart.html',
                                   url=self.continue_shopping_url)

        pipelines = self.build_pipeline()
        index = session.get('cart_pipeline_index', 0)
        pipeline = import_string(pipelines[index])
        return pipeline(self, pipelines, index)._preprocess()

    def set_processor(self, processor=None):
        if not self.processor:
            self.processor = Processor.get_default_processor()
            self.save()

        if not processor:
            return

        if isinstance(processor, Processor):
            self.processor = processor
            self.save()
            return

        try:
            self.processor = Processor.objects.get(id=processor)
        except:
            self.processor = Processor.objects.get(identifier=processor)

        self.save()

    def get_available_processors(self):
        return Processor.objects(published=True)
Esempio n. 7
0
class MediaGalleryAdmin(BaseContentAdmin):
    roles_accepted = ('admin', 'editor', 'author')
    column_searchable_list = ('title', 'body', 'summary')

    form_columns = [
        'title', 'slug', 'channel', 'related_channels', 'summary',
        'content_format', 'body', 'comments_enabled', 'published', 'add_image',
        'contents', 'show_on_channel', 'available_at', 'available_until',
        'tags', 'values', 'template_type'
    ]

    form_args = {
        'body': {
            'widget': TextEditor()
        },
        'slug': {
            'widget': PrepopulatedText(master='title')
        }
    }


admin.register(File, FileAdmin, category=_l('Media'), name=_l("File"))
admin.register(Video, VideoAdmin, category=_l('Media'), name=_l("Video"))
admin.register(Audio, AudioAdmin, category=_l('Media'), name=_l("Audio"))
admin.register(Image, ImageAdmin, category=_l('Media'), name=_l("Image"))
admin.register(MediaGallery,
               MediaGalleryAdmin,
               category=_l('Content'),
               name=_l("Media Gallery"))
Esempio n. 8
0
def configure_admin(app, admin):  # noqa

    custom_index = app.config.get('ADMIN_INDEX_VIEW')
    if custom_index:
        admin.index_view = import_string(custom_index)()
        if isinstance(admin._views[0], BaseIndexView):
            del admin._views[0]
        admin._views.insert(0, admin.index_view)

    admin_config = app.config.get(
        'ADMIN',
        {
            'name': 'Quokka Admin',
            'url': '/admin'
        }
    )

    for k, v in list(admin_config.items()):
        setattr(admin, k, v)

    for entry in app.config.get('FILE_ADMIN', []):
        try:
            admin.add_view(
                FileAdmin(
                    entry['path'],
                    entry['url'],
                    name=_l(entry['name']),
                    category=_l(entry['category']),
                    endpoint=entry['endpoint'],
                    roles_accepted=entry.get('roles_accepted'),
                    editable_extensions=entry.get('editable_extensions')
                )
            )
        except Exception as e:
            app.logger.info(e)

    # register all themes in file manager
    for k, theme in app.theme_manager.themes.items():
        try:

            if k == app.config.get('DEFAULT_THEME'):
                suffix = "(Site theme)"
            elif k == app.config.get('ADMIN_THEME'):
                suffix = "(Admin theme)"
            else:
                suffix = "Theme"

            admin.add_view(
                FileAdmin(
                    theme.static_path,
                    "/_themes/{0}/".format(theme.identifier),
                    name="{0}: {1} static files".format(suffix,
                                                        theme.identifier),
                    category=_l("Files"),
                    endpoint="{0}_static_files".format(theme.identifier),
                    roles_accepted=('admin', "editor"),
                    editable_extensions=app.config.get(
                        'DEFAULT_EDITABLE_EXTENSIONS')
                )
            )
            admin.add_view(
                FileAdmin(
                    theme.templates_path,
                    "/theme_template_files/{0}/".format(theme.identifier),
                    name="{0}: {1} template files".format(suffix,
                                                          theme.identifier),
                    category=_l("Files"),
                    endpoint="{0}_template_files".format(theme.identifier),
                    roles_accepted=('admin', "editor"),
                    editable_extensions=app.config.get(
                        'DEFAULT_EDITABLE_EXTENSIONS')
                )
            )
        except Exception as e:
            app.logger.warning(
                'Error registering %s folder to file admin %s' % (
                    theme.identifier, e
                )
            )

    # adding views
    admin.add_view(InspectorView(category=_l("Settings"),
                                 name=_l("Inspector")))

    # adding extra views
    extra_views = app.config.get('ADMIN_EXTRA_VIEWS', [])
    for view in extra_views:
        admin.add_view(
            import_string(view['module'])(
                category=_l(view.get('category')),
                name=_l(view.get('name'))
            )
        )

    # adding model views
    admin.register(
        Link,
        LinkAdmin,
        category=_l("Content"),
        name=_l("Link")
    )
    admin.register(Config,
                   ConfigAdmin,
                   category=_l("Settings"),
                   name=_l("Config"))
    admin.register(SubContentPurpose,
                   SubContentPurposeAdmin,
                   category=_l("Settings"),
                   name=_l("Sub content purposes"))
    admin.register(ChannelType, ChannelTypeAdmin,
                   category=_l("Settings"), name=_l("Channel type"))
    admin.register(ContentTemplateType,
                   ContentTemplateTypeAdmin,
                   category=_l("Settings"),
                   name=_l("Template type"))
    admin.register(Channel, ChannelAdmin,
                   category=_l("Content"), name=_l("Channel"))

    # avoid registering twice
    if admin.app is None:
        admin.init_app(app)

    return admin
Esempio n. 9
0
        'created_at',
        'sender_email',
        'message',
        'document',
        'status',
    ]

    form_args = {
        'title': {'label': u'主题'},
        'created_at': {'label': u'提交时间'},
        'sender_email': {'label': u'发件人'},
        'message': {'label': u'简介'},
        'document':{'label':u'附件'},
        'status': {'label': u'状态'},
    }

admin.register(BrotherInfo, BrotherInfoAdmin,
               category=_l("Content"), name=_l("BrotherInfo"))
admin.register(BrotherVideos, BrotherVideosAdmin,
               category=_l("Content"), name=_l("BrotherVideos"))
admin.register(BrotherArticles, BrotherArticlesAdmin,
               category=_l("Content"), name=_l("BrotherArticles"))
admin.register(Topic, TopicAdmin, category=_l("Content"), name=_l("Topic"))
admin.register(News, NewsAdmin, category=_l("Content"), name=_l("News"))
admin.register(About, AboutAdmin, category=_l("Content"), name=_l("About"))
admin.register(Banner, BannerAdmin, category=_l("Content"), name=_l("Banner"))
admin.register(BrotherAsk, BrotherAskAdmin,
               category=_l("Content"), name=_l("BrotherAsk"))
admin.register(JoinMessage, JoinMessageAdmin,
               category=_l("Content"), name=_l("JoinMessage"))
Esempio n. 10
0
                }
                post, _ = Post.objects.get_or_create(**post)

                AggregatedTopic(
                    original_url=entry['feedburner_origlink'].encode(
                        'ascii', 'ignore'),
                    blog=blog,
                    post=post).save()


class AggregatedTopicAdmin(ModelAdmin):
    roles_accepted = ('admin', 'editor')
    column_filters = ('date_added', 'original_url', 'blog', 'post')
    column_searchable_list = ['original_url']
    column_list = ('date_added', 'blog', 'original_url', 'post')
    form_columns = ('date_added', 'blog', 'original_url', 'post')

    def on_model_delete(self, topic):
        topic.post.delete()


# Register RSSaggregator models to quokka admin page
admin.register(ExternalBlogs,
               ExternalBlogsAdmin,
               category=_("RSSaggregator"),
               name=_l("External Blogs"))
admin.register(AggregatedTopic,
               AggregatedTopicAdmin,
               category=_("RSSaggregator"),
               name=_l("Aggregated Topics"))
Esempio n. 11
0
    column_list = ('name', 'email', 'active', 'last_login_at', 'login_count')
    form_columns = ('name', 'email', 'roles', 'active', 'newpassword',
                    'confirmed_at', 'last_login_at', 'current_login_at',
                    'last_login_ip', 'current_login_ip', 'login_count',
                    'tagline', 'gravatar_email', 'bio', 'links', 'values')

    form_extra_fields = {"newpassword": TextField(widget=PasswordInput())}

    def on_model_change(self, form, model, is_created):
        if model.newpassword:
            setpwd = model.newpassword
            del model.newpassword
            model.set_password(setpwd, save=True)


class RoleAdmin(ModelAdmin):
    roles_accepted = ('admin', )
    column_list = ('name', 'description', 'values')


class ConnectionAdmin(ModelAdmin):
    roles_accepted = ('admin', )


admin.register(User, UserAdmin, category=_l("Accounts"), name=_l("User"))
admin.register(Role, RoleAdmin, category=_l("Accounts"), name=_l("Roles"))
admin.register(Connection,
               ConnectionAdmin,
               category=_l("Accounts"),
               name=_l("Connection"))
Esempio n. 12
0
    def after_model_change(self, form, model, is_created):
        if not is_created and model.reference:
            model.reference.published = model.published
            if model.tax:
                model.set_reference_tax(float(model.tax))
            model.reference.save()


class ProcessorAdmin(ModelAdmin):
    roles_accepted = ('admin', 'developer')
    column_list = ('identifier', 'title', 'module', 'published')
    form_args = {
        "description": {"widget": TextEditor()},
        "identifier": {"widget": PrepopulatedText(master='title')}
    }
    form_columns = ('title', 'identifier', 'description', 'module',
                    'requires', 'image', 'link', 'config', 'pipeline',
                    'published')
    form_ajax_refs = {
        'image': {'fields': ['title', 'long_slug', 'summary']}
    }

    form_widget_args = {
        'config': {'cols': 40, 'rows': 10, 'style': 'width:500px;'}
    }

admin.register(Cart, CartAdmin, category=_("Cart"), name=_l("Cart"))
admin.register(Processor, ProcessorAdmin, category=_("Cart"),
               name=_l("Processor"))
Esempio n. 13
0
            'channel',
            Channel,
            fields=['title', 'slug', 'long_slug'],
            filters={"long_slug__startswith": "media/image"}
        )
    }


class MediaGalleryAdmin(BaseContentAdmin):
    roles_accepted = ('admin', 'editor', 'author')
    column_searchable_list = ('title', 'body', 'summary')

    form_columns = ['title', 'slug', 'channel', 'related_channels', 'summary',
                    'content_format', 'body',
                    'comments_enabled', 'published', 'add_image', 'contents',
                    'show_on_channel', 'available_at', 'available_until',
                    'tags', 'values', 'template_type']

    form_args = {
        'body': {'widget': TextEditor()},
        'slug': {'widget': PrepopulatedText(master='title')}
    }


admin.register(File, FileAdmin, category=_l('Media'), name=_l("File"))
admin.register(Video, VideoAdmin, category=_l('Media'), name=_l("Video"))
admin.register(Audio, AudioAdmin, category=_l('Media'), name=_l("Audio"))
admin.register(Image, ImageAdmin, category=_l('Media'), name=_l("Image"))
admin.register(MediaGallery, MediaGalleryAdmin,
               category=_l('Content'), name=_l("Media Gallery"))
from quokka import admin
from quokka.core.admin.models import BaseContentAdmin
from quokka.core.widgets import TextEditor, PrepopulatedText
from .models import Post
from quokka.utils.translation import _l


class PostAdmin(BaseContentAdmin):

    column_searchable_list = ('title', 'body', 'summary')

    form_columns = [
        'title', 'slug', 'channel', 'related_channels', 'summary',
        'content_format', 'body', 'authors', 'comments_enabled', 'published',
        'add_image', 'contents', 'show_on_channel', 'available_at',
        'available_until', 'tags', 'values', 'template_type', 'license'
    ]

    form_args = {
        'body': {
            'widget': TextEditor()
        },
        'slug': {
            'widget': PrepopulatedText(master='title')
        }
    }


admin.register(Post, PostAdmin, category=_l("Content"), name=_l("Post"))
Esempio n. 15
0
def configure_admin(app, admin):  # noqa

    custom_index = app.config.get('ADMIN_INDEX_VIEW')
    if custom_index:
        admin.index_view = import_string(custom_index)()
        if isinstance(admin._views[0], BaseIndexView):
            del admin._views[0]
        admin._views.insert(0, admin.index_view)

    admin_config = app.config.get(
        'ADMIN',
        {
            'name': 'Quokka Admin',
            'url': '/admin'
        }
    )

    for k, v in list(admin_config.items()):
        setattr(admin, k, v)

    babel = app.extensions.get('babel')
    if babel:
        try:
            @babel.localeselector
            def get_locale():
                # use default language if set
                if app.config.get('BABEL_DEFAULT_LOCALE'):
                    session['lang'] = app.config.get('BABEL_DEFAULT_LOCALE')
                else:
                    # get best matching language
                    if app.config.get('BABEL_LANGUAGES'):
                        session['lang'] = request.accept_languages.best_match(
                            app.config.get('BABEL_LANGUAGES')
                        )

                return session.get('lang', 'en')

            admin.locale_selector(get_locale)
        except:
            pass  # Exception: Can not add locale_selector second time.

    for entry in app.config.get('FILE_ADMIN', []):
        try:
            admin.add_view(
                FileAdmin(
                    entry['path'],
                    entry['url'],
                    name=_l(entry['name']),
                    category=_l(entry['category']),
                    endpoint=entry['endpoint'],
                    roles_accepted=entry.get('roles_accepted'),
                    editable_extensions=entry.get('editable_extensions')
                )
            )
        except Exception as e:
            logger.info(e)
            #  need to check blueprint endpoisnt colision

    # register all themes in file manager
    for k, theme in app.theme_manager.themes.items():
        try:

            if k == app.config.get('DEFAULT_THEME'):
                suffix = "(Site theme)"
            elif k == app.config.get('ADMIN_THEME'):
                suffix = "(Admin theme)"
            else:
                suffix = "Theme"

            admin.add_view(
                FileAdmin(
                    theme.static_path,
                    "/_themes/{0}/".format(theme.identifier),
                    name="{0}: {1} static files".format(suffix,
                                                        theme.identifier),
                    category=_l("Files"),
                    endpoint="{0}_static_files".format(theme.identifier),
                    roles_accepted=('admin', "editor"),
                    editable_extensions=app.config.get(
                        'DEFAULT_EDITABLE_EXTENSIONS')
                )
            )
            admin.add_view(
                FileAdmin(
                    theme.templates_path,
                    "/theme_template_files/{0}/".format(theme.identifier),
                    name="{0}: {1} template files".format(suffix,
                                                          theme.identifier),
                    category=_l("Files"),
                    endpoint="{0}_template_files".format(theme.identifier),
                    roles_accepted=('admin', "editor"),
                    editable_extensions=app.config.get(
                        'DEFAULT_EDITABLE_EXTENSIONS')
                )
            )
        except:
            pass

    # adding views
    admin.add_view(InspectorView(category=_l("Settings"),
                                 name=_l("Inspector")))

    # adding extra views
    extra_views = app.config.get('ADMIN_EXTRA_VIEWS', [])
    for view in extra_views:
        admin.add_view(
            import_string(view['module'])(
                category=_l(view.get('category')),
                name=_l(view.get('name'))
            )
        )

    # adding model views
    admin.register(
        Link,
        LinkAdmin,
        category=_l("Content"),
        name=_l("Link")
    )
    admin.register(Config,
                   ConfigAdmin,
                   category=_l("Settings"),
                   name=_l("Config"))
    admin.register(SubContentPurpose,
                   SubContentPurposeAdmin,
                   category=_l("Settings"),
                   name=_l("Sub content purposes"))
    admin.register(ChannelType, ChannelTypeAdmin,
                   category=_l("Settings"), name=_l("Channel type"))
    admin.register(ContentTemplateType,
                   ContentTemplateTypeAdmin,
                   category=_l("Settings"),
                   name=_l("Template type"))
    admin.register(Channel, ChannelAdmin,
                   category=_l("Content"), name=_l("Channel"))

    # avoid registering twice
    if admin.app is None:
        admin.init_app(app)

    return admin
Esempio n. 16
0
    form_columns = ('name', 'email', 'roles', 'active', 'newpassword',
                    'confirmed_at',
                    'last_login_at', 'current_login_at', 'last_login_ip',
                    'current_login_ip', 'login_count', 'tagline',
                    'gravatar_email', 'bio', 'links', 'values')

    form_extra_fields = {
        "newpassword": TextField(widget=PasswordInput())
    }

    def on_model_change(self, form, model, is_created):
        if model.newpassword:
            setpwd = model.newpassword
            del model.newpassword
            model.set_password(setpwd, save=True)


class RoleAdmin(ModelAdmin):
    roles_accepted = ('admin',)
    column_list = ('name', 'description', 'values')


class ConnectionAdmin(ModelAdmin):
    roles_accepted = ('admin',)


admin.register(User, UserAdmin, category=_l("Accounts"), name=_l("User"))
admin.register(Role, RoleAdmin, category=_l("Accounts"), name=_l("Roles"))
admin.register(Connection, ConnectionAdmin,
               category=_l("Accounts"), name=_l("Connection"))
Esempio n. 17
0
# coding : utf -8


from quokka import admin
from quokka.core.admin.models import ModelAdmin
from quokka.core.widgets import TextEditor
from .models import Comment
from quokka.utils.translation import _l


class CommentAdmin(ModelAdmin):
    roles_accepted = ("admin", "editor", "moderator")
    column_list = ("path", "author_name", "author_email", "created_at", "published")
    form_columns = [
        "path",
        "author_email",
        "author_name",
        "content_format",
        "body",
        "replies",
        "created_at",
        "created_by",
        "published",
    ]
    form_args = {"body": {"widget": TextEditor()}}


admin.register(Comment, CommentAdmin, category=_l("Content"), name=_l("Comments"))
Esempio n. 18
0
        'available_at': ModelAdmin.formatters.get('datetime'),
        'values': ModelAdmin.formatters.get('ul'),
        'status': ModelAdmin.formatters.get('status'),
    }

    column_formatters_args = {
        'ul': {
            'values': {
                'placeholder': u"{item.campaign.title} - {item.value}",
                'style': "min-width:200px;max-width:300px;"
            }
        },
        'status': {
            'status': {
                'labels': {
                    'confirmed': 'success',
                    'checked_out': 'warning',
                    'cancelled': 'important',
                    'completed': 'success'
                },
                'style': 'min-height:18px;'
            }
        }
    }


admin.register(Campaign, CampaignAdmin,
               category=_("Fundraising"), name=_l("Campaign"))
admin.register(Donation, DonationAdmin,
               category=_("Fundraising"), name=_l("Donation"))
Esempio n. 19
0
class ExternalBlogsAdmin(ModelAdmin):
    roles_accepted = ('admin')
    column_filters = ('name', 'root_url')
    column_searchable_list = ('name', 'root_url', 'feeds_url')
    column_list = ('name', 'root_url', 'feeds_url', 'channel')
    form_columns = ('name', 'root_url', 'feeds_url', 'channel')

    __content_format_dict = {
        'text/plain': 'plaintext',
        'plaintext': 'plaintext',
        'text/html': 'html',
        'html': 'html',
        'text/markdown': 'markdown',
        'markdown': 'markdown',
    }

    @action('get_external_posts', _l('Get external topics'))
    def get_external_posts(self, ids):
        blogs = ExternalBlogs.objects(id__in=ids)

        for blog in blogs:
            feed = feedparser.parse(blog.feeds_url)

            for entry in feed['entries']:

                # If already exist a topic with this url
                if AggregatedTopic.objects(
                        original_url=entry['feedburner_origlink']).first():
                    continue  # Go to next iteration

                body = '{sumary}... <a href={link}>Continue reading</a>'.format(
                    sumary=entry['summary'].encode('ascii', 'ignore'),
                    link=entry['feedburner_origlink'].encode(
                        'ascii', 'ignore'))
                content_format = self.__content_format_dict[entry['content'][0]
                                                            ['type']]

                post = {
                    "title":
                    entry['title'].encode('ascii', 'ignore'),
                    "slug":
                    entry['title'].replace(' ', '-').encode('ascii', 'ignore'),
                    "summary":
                    entry['summary'],
                    "content_format":
                    content_format,
                    "body":
                    body,
                    "channel":
                    blog.channel,
                    "tags": [
                        tag['term'].encode('ascii', 'ignore')
                        for tag in entry['tags']
                    ],
                    "published":
                    True
                }
                post, _ = Post.objects.get_or_create(**post)

                AggregatedTopic(
                    original_url=entry['feedburner_origlink'].encode(
                        'ascii', 'ignore'),
                    blog=blog,
                    post=post).save()
def configure_admin(app, admin):  # noqa

    custom_index = app.config.get('ADMIN_INDEX_VIEW')
    if custom_index:
        admin.index_view = import_string(custom_index)()
        if isinstance(admin._views[0], BaseIndexView):
            del admin._views[0]
        admin._views.insert(0, admin.index_view)

    admin_config = app.config.get('ADMIN', {
        'name': 'Quokka Admin',
        'url': '/admin'
    })

    for k, v in list(admin_config.items()):
        setattr(admin, k, v)

    for entry in app.config.get('FILE_ADMIN', []):
        try:
            admin.add_view(
                FileAdmin(
                    entry['path'],
                    entry['url'],
                    name=_l(entry['name']),
                    category=_l(entry['category']),
                    endpoint=entry['endpoint'],
                    roles_accepted=entry.get('roles_accepted'),
                    editable_extensions=entry.get('editable_extensions')))
        except Exception as e:
            app.logger.info(e)

    # register all themes in file manager
    for k, theme in app.theme_manager.themes.items():
        try:

            if k == app.config.get('DEFAULT_THEME'):
                suffix = "(Site theme)"
            elif k == app.config.get('ADMIN_THEME'):
                suffix = "(Admin theme)"
            else:
                suffix = "Theme"

            admin.add_view(
                FileAdmin(theme.static_path,
                          "/_themes/{0}/".format(theme.identifier),
                          name="{0}: {1} static files".format(
                              suffix, theme.identifier),
                          category=_l("Files"),
                          endpoint="{0}_static_files".format(theme.identifier),
                          roles_accepted=('admin', "editor"),
                          editable_extensions=app.config.get(
                              'DEFAULT_EDITABLE_EXTENSIONS')))
            admin.add_view(
                FileAdmin(
                    theme.templates_path,
                    "/theme_template_files/{0}/".format(theme.identifier),
                    name="{0}: {1} template files".format(
                        suffix, theme.identifier),
                    category=_l("Files"),
                    endpoint="{0}_template_files".format(theme.identifier),
                    roles_accepted=('admin', "editor"),
                    editable_extensions=app.config.get(
                        'DEFAULT_EDITABLE_EXTENSIONS')))
        except Exception as e:
            app.logger.warning('Error registering %s folder to file admin %s' %
                               (theme.identifier, e))

    # adding views
    admin.add_view(InspectorView(category=_l("Settings"),
                                 name=_l("Inspector")))

    # adding extra views
    extra_views = app.config.get('ADMIN_EXTRA_VIEWS', [])
    for view in extra_views:
        admin.add_view(
            import_string(view['module'])(category=_l(view.get('category')),
                                          name=_l(view.get('name'))))

    # adding model views
    admin.register(Link, LinkAdmin, category=_l("Content"), name=_l("Link"))
    admin.register(Config,
                   ConfigAdmin,
                   category=_l("Settings"),
                   name=_l("Config"))
    admin.register(SubContentPurpose,
                   SubContentPurposeAdmin,
                   category=_l("Settings"),
                   name=_l("Sub content purposes"))
    admin.register(ChannelType,
                   ChannelTypeAdmin,
                   category=_l("Settings"),
                   name=_l("Channel type"))
    admin.register(ContentTemplateType,
                   ContentTemplateTypeAdmin,
                   category=_l("Settings"),
                   name=_l("Template type"))
    admin.register(Channel,
                   ChannelAdmin,
                   category=_l("Content"),
                   name=_l("Channel"))

    # avoid registering twice
    if admin.app is None:
        admin.init_app(app)

    return admin
Esempio n. 21
0
        'replies', 'created_at', 'created_by', 'published',
        'viewed_by_moderator'
    ]
    form_args = {
        'body': {
            'widget': TextEditor()
        },
        'viewed_by_moderator': {
            'widget': widgets.HiddenInput()
        }
    }
    column_filters = [
        ViewedByModeratorFilter(
            column=Comment.viewed_by_moderator,
            name='viewed by moderator',
        )
    ]

    def get_one(self, _id):
        rtn = super(CommentAdmin, self).get_one(_id)
        if not rtn.viewed_by_moderator:
            rtn.viewed_by_moderator = True
            rtn.save()
        return rtn


admin.register(Comment,
               CommentAdmin,
               category=_l('Content'),
               name=_l("Comments"))
Esempio n. 22
0
def configure_admin(app, admin):  # noqa

    custom_index = app.config.get('ADMIN_INDEX_VIEW')
    if custom_index:
        admin.index_view = import_string(custom_index)()
        if isinstance(admin._views[0], BaseIndexView):
            del admin._views[0]
        admin._views.insert(0, admin.index_view)

    admin_config = app.config.get('ADMIN', {
        'name': 'Quokka Admin',
        'url': '/admin'
    })

    for k, v in list(admin_config.items()):
        setattr(admin, k, v)

    babel = app.extensions.get('babel')
    if babel:
        try:

            @babel.localeselector
            def get_locale():
                # use default language if set
                if app.config.get('BABEL_DEFAULT_LOCALE'):
                    session['lang'] = app.config.get('BABEL_DEFAULT_LOCALE')
                else:
                    # get best matching language
                    if app.config.get('BABEL_LANGUAGES'):
                        session['lang'] = request.accept_languages.best_match(
                            app.config.get('BABEL_LANGUAGES'))

                return session.get('lang', 'en')

            admin.locale_selector(get_locale)
        except:
            pass  # Exception: Can not add locale_selector second time.

    for entry in app.config.get('FILE_ADMIN', []):
        try:
            admin.add_view(
                FileAdmin(
                    entry['path'],
                    entry['url'],
                    name=_l(entry['name']),
                    category=_l(entry['category']),
                    endpoint=entry['endpoint'],
                    roles_accepted=entry.get('roles_accepted'),
                    editable_extensions=entry.get('editable_extensions')))
        except Exception as e:
            logger.info(e)
            #  need to check blueprint endpoisnt colision

    # register all themes in file manager
    for k, theme in app.theme_manager.themes.items():
        try:

            if k == app.config.get('DEFAULT_THEME'):
                suffix = "(Site theme)"
            elif k == app.config.get('ADMIN_THEME'):
                suffix = "(Admin theme)"
            else:
                suffix = "Theme"

            admin.add_view(
                FileAdmin(theme.static_path,
                          "/_themes/{0}/".format(theme.identifier),
                          name="{0}: {1} static files".format(
                              suffix, theme.identifier),
                          category=_l("Files"),
                          endpoint="{0}_static_files".format(theme.identifier),
                          roles_accepted=('admin', "editor"),
                          editable_extensions=app.config.get(
                              'DEFAULT_EDITABLE_EXTENSIONS')))
            admin.add_view(
                FileAdmin(
                    theme.templates_path,
                    "/theme_template_files/{0}/".format(theme.identifier),
                    name="{0}: {1} template files".format(
                        suffix, theme.identifier),
                    category=_l("Files"),
                    endpoint="{0}_template_files".format(theme.identifier),
                    roles_accepted=('admin', "editor"),
                    editable_extensions=app.config.get(
                        'DEFAULT_EDITABLE_EXTENSIONS')))
        except:
            pass

    # adding views
    admin.add_view(InspectorView(category=_l("Settings"),
                                 name=_l("Inspector")))

    # adding extra views
    extra_views = app.config.get('ADMIN_EXTRA_VIEWS', [])
    for view in extra_views:
        admin.add_view(
            import_string(view['module'])(category=_l(view.get('category')),
                                          name=_l(view.get('name'))))

    # adding model views
    admin.register(Link, LinkAdmin, category=_l("Content"), name=_l("Link"))
    admin.register(Config,
                   ConfigAdmin,
                   category=_l("Settings"),
                   name=_l("Config"))
    admin.register(SubContentPurpose,
                   SubContentPurposeAdmin,
                   category=_l("Settings"),
                   name=_l("Sub content purposes"))
    admin.register(ChannelType,
                   ChannelTypeAdmin,
                   category=_l("Settings"),
                   name=_l("Channel type"))
    admin.register(ContentTemplateType,
                   ContentTemplateTypeAdmin,
                   category=_l("Settings"),
                   name=_l("Template type"))
    admin.register(Channel,
                   ChannelAdmin,
                   category=_l("Content"),
                   name=_l("Channel"))

    # avoid registering twice
    if admin.app is None:
        admin.init_app(app)

    return admin
Esempio n. 23
0
# coding : utf -8

from quokka import admin
from quokka.core.admin.models import BaseContentAdmin
from quokka.core.widgets import TextEditor, PrepopulatedText
from .models import Post
from quokka.utils.translation import _l


class PostAdmin(BaseContentAdmin):

    column_searchable_list = ('title', 'body', 'summary')

    form_columns = ['title', 'slug', 'channel', 'related_channels', 'summary',
                    'content_format', 'body', 'authors',
                    'comments_enabled', 'published', 'add_image', 'contents',
                    'show_on_channel', 'available_at', 'available_until',
                    'tags', 'values', 'template_type', 'license']

    form_args = {
        'body': {'widget': TextEditor()},
        'slug': {'widget': PrepopulatedText(master='title')}
    }


admin.register(Post, PostAdmin, category=_l("Content"), name=_l("Post"))