Пример #1
0
def redirectWhenNotAuthenticated(request, context, next_title=None):
    if not request.user.is_authenticated():
        if context.get('current_url', '').startswith('/ajax/'):
            raise HttpRedirectException(u'/signup/')
        raise HttpRedirectException(
            u'/signup/{}'.format((u'?next={}{}'.format(
                context['current_url'], u'&next_title={}'.
                format(unicode(next_title)) if next_title else u'')
                                  ) if 'current_url' in context else ''))
Пример #2
0
 def get_item(self, request, pk):
     if pk == 'me':
         if request.user.is_authenticated():
             pk = request.user.id
         else:
             from magi.middleware.httpredirect import HttpRedirectException
             raise HttpRedirectException('/signup/')
     return {'pk': pk}
Пример #3
0
def block(request, pk, unblock=False):
    context = getGlobalContext(request)
    redirectWhenNotAuthenticated(request, context, next_title=_('Settings'))
    user = get_object_or_404(models.User.objects.select_related('preferences'),
                             pk=pk)
    block = True
    if request.user.preferences.blocked.filter(pk=user.pk).exists():
        block = False
        context['info_message'] = _(u'You blocked {username}.').format(
            username=user.username)
    context['blocking'] = block
    title = _(u'Block {username}').format(
        username=user.username) if block else _(u'Unblock {username}').format(
            username=user.username)
    context['page_title'] = title
    context['extends'] = 'base.html'
    context['form'] = Confirm()
    context['alert_message'] = (_(
        u'Are you sure you want to block {username}? You will not be able to see any content created by {username}.'
    ) if block else _(u'Are you sure you want to unblock {username}?')).format(
        username=user.username)
    context['alert_type'] = 'danger'
    context['alert_flaticon'] = 'fingers'
    if request.method == 'POST':
        context['form'] = Confirm(request.POST)
        if context['form'].is_valid():
            if block:
                request.user.preferences.blocked.add(user)
                request.user.preferences.following.remove(user)
                user.preferences.following.remove(request.user)
                redirect_url = context['current_url']
            else:
                request.user.preferences.blocked.remove(user)
                redirect_url = user.item_url
            if 'next' in request.GET:
                redirect_url = request.GET['next']
            request.user.preferences.update_cache('blocked_ids')
            request.user.preferences.save()
            user.preferences.update_cache('blocked_by_ids')
            user.preferences.save()
            raise HttpRedirectException(redirect_url)
    context['form'].submit_title = title
    return render(request, 'pages/block.html', context)
Пример #4
0
def item_view(request,
              name,
              collection,
              pk=None,
              reverse=None,
              ajax=False,
              item=None,
              extra_filters={},
              shortcut_url=None,
              **kwargs):
    """
    Either pk or reverse required.
    """
    context = collection.item_view.get_global_context(request)
    collection.item_view.check_permissions(request, context)
    queryset = collection.item_view.get_queryset(
        collection.queryset, _get_filters(request.GET, extra_filters), request)
    if not pk and reverse:
        options = collection.item_view.reverse_url(reverse)
    else:
        options = collection.item_view.get_item(request, pk)
    context['item'] = get_one_object_or_404(queryset, **
                                            options) if not item else item
    collection.item_view.check_owner_permissions(request, context,
                                                 context['item'])

    if request.user.is_authenticated() and collection.blockable:
        # Blocked
        if context[
                'item'].owner_id in request.user.preferences.cached_blocked_ids:
            if ajax:
                try:
                    username = context['item'].owner.username
                except AttributeError:
                    username = _('this user')
                context['item'].blocked_message = _(
                    u'You blocked {username}.').format(username=username)
                context['item'].unblock_button = _(
                    u'Unblock {username}').format(username=username)
                return render(request,
                              'items/default_blocked_template_in_list.html',
                              context)
            raise HttpRedirectException(u'/block/{id}/?next={next_url}'.format(
                id=context['item'].owner_id,
                next_url=context['current_url'],
            ))
        # Blocked by
        elif context[
                'item'].owner_id in request.user.preferences.cached_blocked_by_ids:
            raise PermissionDenied()

    if shortcut_url is not None:
        context['shortcut_url'] = shortcut_url
    context['ajax'] = ajax
    context['name'] = name
    context['page_title'] = u'{item} - {title}'.format(title=collection.title,
                                                       item=context['item'])
    context['js_files'] = collection.item_view.js_files
    context['reportable'] = collection.reportable
    context['share_image'] = _get_share_image(context,
                                              collection.item_view,
                                              item=context['item'])
    context['comments_enabled'] = collection.item_view.comments_enabled
    context['share_enabled'] = collection.item_view.share_enabled
    context['item_padding'] = collection.item_view.item_padding
    context['item_template'] = collection.item_view.template
    context['full_width'] = collection.item_view.full_width
    context['ajax_callback'] = collection.item_view.ajax_callback
    context['hide_icons'] = collection.item_view.hide_icons
    context['collection'] = collection
    if context['item_template'] == 'default':
        context['top_illustration'] = collection.item_view.top_illustration
        context['item_fields'] = collection.item_view.to_fields(
            context['item'], request=request)

    # Ajax items reloader
    if not ajax and collection.item_view.auto_reloader and collection.item_view.ajax:
        context['ajax_reload_url'] = context['item'].ajax_item_url
        context['reload_urls_start_with'] = [
            u'/{}/edit/'.format(collection.plural_name)
        ]
        if collection.collectible_collections:
            context['reload_urls_start_with'] += [
                cc.get_add_url()
                for cc in collection.collectible_collections.values()
            ]

    context['include_below_item'] = False
    context['show_item_buttons'] = collection.item_view.show_item_buttons
    context['item'].request = request
    context[
        'item'].show_item_buttons_justified = collection.item_view.show_item_buttons_justified
    context[
        'item'].show_item_buttons_as_icons = collection.item_view.show_item_buttons_as_icons
    context[
        'item'].show_item_buttons_in_one_line = collection.item_view.show_item_buttons_in_one_line
    context['item'].buttons_to_show = collection.item_view.buttons_per_item(
        request, context, context['item'])
    if 'only_show_buttons' in request.GET:
        only_show_buttons = request.GET['only_show_buttons'].split(',')
        for button_name, button in context['item'].buttons_to_show.items():
            if button_name not in only_show_buttons:
                button['show'] = False
    if collection.item_view.show_item_buttons and [
            True for b in context['item'].buttons_to_show.values()
            if b['show'] and b['has_permissions']
    ]:
        context['include_below_item'] = True

    collection.item_view.extra_context(context)
    if ajax:
        context['include_template'] = 'items/{}'.format(
            context['item_template'])
        return render(request, 'ajax.html', context)
    return render(request, 'collections/item_view.html', context)
Пример #5
0
def edit_view(request,
              name,
              collection,
              pk,
              extra_filters={},
              ajax=False,
              shortcut_url=None,
              **kwargs):
    context = collection.edit_view.get_global_context(request)
    context['is_translate'] = 'translate' in request.GET
    if context['is_translate']:
        collection.edit_view.check_translate_permissions(request, context)
    else:
        collection.edit_view.check_permissions(request, context)
    context['is_reported'] = 'is_reported' in request.GET
    context = _modification_view(context, name, collection.edit_view, ajax)
    queryset = collection.edit_view.get_queryset(
        collection.queryset, _get_filters(request.GET, extra_filters), request)
    instance = get_one_object_or_404(
        queryset, **collection.edit_view.get_item(request, pk))
    context['type'] = None
    collection.edit_view.check_owner_permissions(request, context, instance)
    if context['is_translate']:
        formClass = collection.edit_view.translate_form_class
        context['icontitle'] = 'translate'
    elif collection.types:
        type = instance.type
        context['type'] = type
        collection.edit_view.check_type_permissions(request,
                                                    context,
                                                    type=type,
                                                    item=instance)
        formClass = collection.types[type].get('form_class',
                                               collection.edit_view.form_class)
        context['imagetitle'] = collection.types[type].get(
            'image', collection.image)
        context['icontitle'] = collection.types[type].get(
            'icon', collection.icon)
    else:
        formClass = collection.edit_view.form_class
        context['imagetitle'] = collection.image
        context['icontitle'] = collection.icon
    if str(_type(formClass)) == '<type \'instancemethod\'>':
        formClass = formClass(request, context)
    allowDelete = not context[
        'is_translate'] and collection.edit_view.allow_delete and 'disable_delete' not in request.GET
    form = formClass(instance=instance,
                     request=request,
                     ajax=ajax,
                     collection=collection)
    if allowDelete:
        formDelete = ConfirmDelete(initial={
            'thing_to_delete': instance.pk,
        },
                                   request=request,
                                   instance=instance,
                                   collection=collection)
    form = formClass(instance=instance,
                     request=request,
                     ajax=ajax,
                     collection=collection)
    if allowDelete and request.method == 'POST' and u'delete_{}'.format(
            collection.name) in request.POST:
        formDelete = ConfirmDelete(request.POST,
                                   request=request,
                                   instance=instance,
                                   collection=collection)
        if formDelete.is_valid():
            collection.edit_view.before_delete(request, instance, ajax)
            redirectURL = collection.edit_view.redirect_after_delete(
                request, instance, ajax)
            instance.delete()
            raise HttpRedirectException(redirectURL)
    elif request.method == 'POST':
        form = formClass(request.POST,
                         request.FILES,
                         instance=instance,
                         request=request,
                         ajax=ajax,
                         collection=collection)
        if form.is_valid():
            instance = form.save(commit=False)
            instance = collection.edit_view.before_save(request, instance)
            instance.save()
            if collection.edit_view.savem2m and not context['is_translate']:
                form.save_m2m()
            instance = collection.edit_view.after_save(request, instance)
            redirectURL = collection.edit_view.redirect_after_edit(
                request, instance, ajax)
            raise HttpRedirectException(redirectURL)
    cuteFormFieldsForContext(
        collection.edit_view.filter_cuteform,
        context,
        form=form,
        prefix=u'[data-form-name="edit_{}"] '.format(collection.name),
        ajax=ajax,
    )
    if shortcut_url is not None:
        context['shortcut_url'] = shortcut_url
    context['forms'] = OrderedDict()
    context[
        'action_sentence'] = instance.edit_sentence  # Used as the page title
    form.action_sentence = instance.edit_sentence
    context['item'] = instance
    context['item'].request = request
    context['share_image'] = _get_share_image(context,
                                              collection.edit_view,
                                              item=context['item'])
    _modification_views_page_titles(instance.edit_sentence, context,
                                    unicode(instance))
    context['ajax_callback'] = collection.edit_view.ajax_callback
    context['forms'][u'edit_{}'.format(collection.name)] = form
    context['collection'] = collection
    if allowDelete:
        formDelete.alert_message = _(
            'You can\'t cancel this action afterwards.')
        formDelete.action_sentence = instance.delete_sentence
        formDelete.form_title = u'{}: {}'.format(instance.delete_sentence,
                                                 unicode(instance))
        if 'js_variables' not in context or not context['js_variables']:
            context['js_variables'] = OrderedDict()
        context['js_variables']['show_cascade_before_delete'] = jsv(
            collection.edit_view.show_cascade_before_delete)
        context['forms'][u'delete_{}'.format(collection.name)] = formDelete

    collection.edit_view.extra_context(context)
    if ajax:
        context['include_template'] = 'collections/modification_view'
        context['extends'] = 'ajax.html'
        context['ajax'] = True
    return render(request, 'collections/modification_view.html', context)
Пример #6
0
def add_view(request,
             name,
             collection,
             type=None,
             ajax=False,
             shortcut_url=None,
             **kwargs):
    context = collection.add_view.get_global_context(request)
    collection.add_view.check_permissions(request, context)
    context = _modification_view(context, name, collection.add_view, ajax)
    with_types = False
    if shortcut_url is not None:
        context['shortcut_url'] = shortcut_url
    context['next'] = request.GET.get('next', None)
    context['next_title'] = request.GET.get('next_title', None)
    context['type'] = None
    after_title = None
    if type is not None and collection.types:
        if type not in collection.types:
            raise Http404
        with_types = True
        context['type'] = type
        collection.add_view.check_type_permissions(request, context, type=type)
        formClass = collection.types[type].get('form_class',
                                               collection.add_view.form_class)
        context['imagetitle'] = collection.types[type].get(
            'image', collection.image)
        context['icontitle'] = collection.types[type].get(
            'icon', collection.icon)
        after_title = collection.types[type].get('title', type)
    else:
        formClass = collection.add_view.form_class
        context['imagetitle'] = collection.image
        context['icontitle'] = collection.icon
    if str(_type(formClass)) == '<type \'instancemethod\'>':
        formClass = formClass(request, context)
    if request.method == 'GET':
        form = formClass(
            request=request, ajax=ajax,
            collection=collection) if not with_types else formClass(
                request=request, ajax=ajax, collection=collection, type=type)
    elif request.method == 'POST':
        form = formClass(
            request.POST,
            request.FILES,
            request=request,
            ajax=ajax,
            collection=collection) if not with_types else formClass(
                request.POST,
                request.FILES,
                request=request,
                ajax=ajax,
                collection=collection,
                type=type)
        if form.is_valid():
            instance = form.save(commit=False)
            instance = collection.add_view.before_save(request,
                                                       instance,
                                                       type=type)
            instance.save()
            if collection.add_view.savem2m:
                form.save_m2m()
            instance = collection.add_view.after_save(request,
                                                      instance,
                                                      type=type)
            if collection.add_view.allow_next and context['next']:
                raise HttpRedirectException(context['next'])
            redirectURL = collection.add_view.redirect_after_add(
                request, instance, ajax)
            if context['next']:
                redirectURL += '{}next={}&next_title={}'.format(
                    '&' if '?' in redirectURL else '?',
                    context['next'],
                    context['next_title'] if context['next_title'] else '',
                )
            raise HttpRedirectException(redirectURL)
    cuteFormFieldsForContext(
        collection.add_view.filter_cuteform,
        context,
        form=form,
        prefix=u'[data-form-name="add_{}"] '.format(collection.name),
        ajax=ajax,
    )
    _modification_views_page_titles(collection.add_sentence, context,
                                    after_title)
    context['action_sentence'] = collection.add_sentence  # Used in page title
    form.action_sentence = collection.add_sentence  # Genericity when we have multiple forms
    context['share_image'] = _get_share_image(context, collection.add_view)
    context['forms'] = {u'add_{}'.format(collection.name): form}
    context['ajax_callback'] = collection.add_view.ajax_callback
    context['collection'] = collection
    if collection.add_view.alert_duplicate:
        context['alert_message'] = _(
            'Make sure the {thing} you\'re about to add doesn\'t already exist.'
        ).format(thing=_(collection.title.lower()))
        context['alert_button_link'] = context['list_url']
        context['alert_button_string'] = _(collection.plural_title)

    collection.add_view.extra_context(context)
    if ajax:
        context['include_template'] = 'collections/modification_view'
        context['extends'] = 'ajax.html'
        context['ajax'] = True
    return render(request, 'collections/modification_view.html', context)
Пример #7
0
def redirectToProfile(request, account=None):
    raise HttpRedirectException(u'/user/{}/{}/'.format(
        request.user.id, request.user.username,
        '#{}'.format(account.id) if account else ''))