示例#1
0
文件: views.py 项目: mxabierto/datal
def activate(request):
    if request.method == "GET":
        form = forms.ActivateUserForm(request.GET)
        ticket = request.GET.get("ticket")
        user_pass_ticket = get_object_or_404(UserPassTickets, type=TicketChoices.USER_ACTIVATION, uuid=ticket)
        return render_to_response("accounts/activate.html", locals())

    elif request.method == "POST":
        form = forms.ActivateUserForm(request.POST)
        if form.is_valid():
            ticket = form.cleaned_data.get("ticket")
            password = form.cleaned_data.get("password")
            user_pass_ticket = get_object_or_404(UserPassTickets, type=TicketChoices.USER_ACTIVATION, uuid=ticket)
            user = user_pass_ticket.user
            user.password = password
            user.save()
            user_pass_ticket.delete()

            request.session["user_id"] = user.id
            request.session.set_expiry(0)

            return redirect("accounts.landing")

        else:
            return render_to_response("accounts/activate.html", locals())
示例#2
0
文件: views.py 项目: mxabierto/datal
def embed(request, guid):
    """
    Show an embed microsite view
    """
    account = request.account
    preferences = request.preferences
    msprotocol = "https" if account.get_preference("account.microsite.https") else "http"
    base_uri = msprotocol + "://" + preferences["account_domain"]

    try:
        visualization_revision = VisualizationDBDAO().get(preferences["account_language"], published=True, guid=guid)

        datastream = DataStreamDBDAO().get(
            preferences["account_language"], datastream_revision_id=visualization_revision["datastream_revision_id"]
        )
    except:
        return render_to_response("viewChart/embed404.html", {"settings": settings, "request": request})

    # VisualizationHitsDAO(visualization_revision.visualization).add(ChannelTypes.WEB)
    VisualizationHitsDAO(visualization_revision).add(ChannelTypes.WEB)

    width = request.REQUEST.get("width", False)  # TODO get default value from somewhere
    height = request.REQUEST.get("height", False)  # TODO get default value from somewhere

    visualization_revision_parameters = RequestProcessor(request).get_arguments(visualization_revision["parameters"])
    visualization_revision_parameters["pId"] = visualization_revision["datastream_revision_id"]

    command = AbstractCommandFactory("microsites").create("invoke", "vz", (visualization_revision_parameters,))
    json, type = command.run()
    visualization_revision_parameters = urllib.urlencode(visualization_revision_parameters)

    return render_to_response("viewChart/embed.html", locals())
示例#3
0
文件: views.py 项目: anukat2015/datal
def embed(request, guid):
    """
    Show an embed microsite view
    """
    account = request.account
    preferences = request.preferences
    msprotocol = 'https' if account.get_preference('account.microsite.https') else 'http'
    base_uri = msprotocol + '://' + preferences['account_domain']

    try:
        visualization_revision = VisualizationDBDAO().get(request.user,
            published=True, guid=guid )

        datastream = DataStreamDBDAO().get(request.user,
            datastream_revision_id=visualization_revision["datastream_revision_id"]
        )
    except:
        return render_to_response('viewChart/embed404.html',{'settings': settings, 'request' : request})

    #VisualizationHitsDAO(visualization_revision.visualization).add(ChannelTypes.WEB)
    VisualizationHitsDAO(visualization_revision).add(ChannelTypes.WEB)

    width = request.REQUEST.get('width', False) # TODO get default value from somewhere
    height = request.REQUEST.get('height', False) # TODO get default value from somewhere

    visualization_revision_parameters = RequestProcessor(request).get_arguments(visualization_revision["parameters"])
    visualization_revision_parameters['pId'] = visualization_revision["datastream_revision_id"]
    
    command = AbstractCommandFactory('microsites').create("invoke", 
            "vz", (visualization_revision_parameters,))
    json, type = command.run()
    visualization_revision_parameters = urllib.urlencode(visualization_revision_parameters)

    return render_to_response('viewChart/embed.html', locals())
示例#4
0
文件: views.py 项目: PhiRequiem/datal
def action_embed(request, guid):
    """
    Show an embed microsite view
    """
    account = request.account
    preferences = request.preferences
    base_uri = 'http://' + preferences['account_domain']

    try:
        visualizationrevision_id = VisualizationRevision.objects.get_last_published_by_guid(guid)
        visualization_revision = VisualizationDBDAO().get(
            preferences['account_language'],
            visualization_revision_id=visualizationrevision_id
        )

        datastream = DataStreamDBDAO().get(
            preferences['account_language'],
            datastream_revision_id=visualization_revision["datastream_revision_id"]
        )
    except:
        return render_to_response('viewChart/embed404.html',{'settings': settings, 'request' : request})

    # VisualizationHitsDAO(visualization_revision.visualization).add(ChannelTypes.WEB)
    width = request.REQUEST.get('width', False) # TODO get default value from somewhere
    height = request.REQUEST.get('height', False) # TODO get default value from somewhere

    visualization_revision_parameters = RequestProcessor(request).get_arguments(visualization_revision["parameters"])
    visualization_revision_parameters['pId'] = visualization_revision["datastream_revision_id"]
    json, type = invoke(visualization_revision_parameters)
    visualization_revision_parameters = urllib.urlencode(visualization_revision_parameters)

    return render_to_response('viewChart/embed.html', locals())
示例#5
0
文件: views.py 项目: mxabierto/datal
def signin(request, admin_url=""):
    auth_manager = request.auth_manager
    if not auth_manager.is_anonymous():
        return HttpResponseRedirect(reverse("accounts.landing"))

    form = forms.SignInForm(request.GET, initial={"admin_url": admin_url})
    if admin_url:
        try:
            account_id = Preference.objects.get_account_id_by_known_key_and_value("account.url", admin_url)
            account = Account.objects.get(pk=account_id)
            preferences = account.get_preferences()
        except (Preference.DoesNotExist, Account.DoesNotExist):
            raise Http404
        return render_to_response("accounts/signIn.html", locals())
    else:
        return render_to_response("accounts/signIn.html", locals())
示例#6
0
文件: views.py 项目: mxabierto/datal
def forgot_password(request):
    if request.method == "GET":
        return render_to_response("accounts/forgotPassword.html", locals())

    if request.method == "POST":
        ok = False

        try:
            user_identification = request.REQUEST["identification"]
        except:
            raise Http404

        try:
            user = User.objects.get(Q(nick=user_identification) | Q(email=user_identification))
        except:
            user = ""

        if user:
            uuid = uuid4()
            pass_ticket = UserPassTickets.objects.create(uuid=uuid, user_id=user.id, type="PASS")
            url = get_domain_with_protocol("workspace") + "/recovery?id=" + str(uuid)
            DjangoMailService().send_forgot_password_mail(user, url)
            message = ugettext("FORGOT-ACTIVATION-EMAIL")
            ok = True
        else:
            message = ugettext("FORGOT-USER-NOFOUND")

        return HttpResponse(
            '{"p_message":"' + message + '", "ok" :"' + str(ok) + '" }', content_type="application/json"
        )
示例#7
0
文件: views.py 项目: mxabierto/datal
def create(request):
    
    if request.method == 'GET':
        datastream_revision_id = request.GET.get('datastream_revision_id', None)
        try:
            datastream_rev = DataStreamDBDAO().get(
                request.user.language,
                datastream_revision_id=datastream_revision_id,
                published=False
            )
        except DataStreamRevision.DoesNotExist:
            raise DataStreamNotFoundException()

        return render_to_response('createVisualization/index.html', dict(
            request=request,
            datastream_revision=datastream_rev
        ))

    elif request.method == 'POST':
        """ save new or update dataset """
        # Valido que llegue el ID de la revision del datastream
        datastream_rev_id = request.GET.get('datastream_revision_id', None)
        if not datastream_rev_id:
            raise Http404
        datastream_rev = DataStreamRevision.objects.get(pk=datastream_rev_id)

        # Formulario
        form = VisualizationForm(request.POST)
        if not form.is_valid():
            logger.info(form._errors)
            raise VisualizationSaveException('Invalid form data: %s' % str(form.errors.as_text()))

        response = form.save(request, datastream_rev=datastream_rev)

        return JSONHttpResponse(json.dumps(response))
示例#8
0
文件: views.py 项目: mxabierto/datal
def edit(request, revision_id=None):
    if request.method == 'GET':
        visualization_rev = VisualizationDBDAO().get(
            request.auth_manager.language,
            visualization_revision_id=revision_id
        )
        datastream_rev = DataStreamDBDAO().get(
            request.auth_manager.language,
            datastream_revision_id=visualization_rev['datastream_revision_id'])
        return render_to_response('createVisualization/index.html', dict(
            request=request,
            datastream_revision=datastream_rev,
            visualization_revision=visualization_rev
        ))

    elif request.method == 'POST':
        """ save new or update dataset """
        # Formulario
        form = VisualizationForm(request.POST)
        if not form.is_valid():
            logger.info(form.errors)
            raise VisualizationSaveException('Invalid form data: %s' % str(form.errors.as_text()))

        visualization_rev = VisualizationDBDAO().get(
            request.auth_manager.language,
            visualization_revision_id=revision_id
        )
        response = form.save(request, visualization_rev=visualization_rev)

        # Signal
        visualization_changed.send_robust(sender='edit_view', id=visualization_rev['visualization_id'],
                                          rev_id=visualization_rev['visualization_revision_id'])

        return JSONHttpResponse(json.dumps(response))
示例#9
0
文件: views.py 项目: mxabierto/datal
def get_new_css(request, id):
    try:
        account = request.account
        preferences = account.get_preferences()
        keys = [
            'account.title.color',
            'account.button.bg.color',
            'account.button.border.color',
            'account.button.font.color',
            'account.mouseover.bg.color',
            'account.mouseover.border.color',
            'account.mouseover.title.color',
            'account.mouseover.text.color'
        ]
        keys_copy = list(keys)
        preferences.load(keys)

        for key in keys_copy:
            if preferences[key.replace('.', '_')]:
                return render_to_response('css_branding/branding.css', locals(), mimetype = 'text/css')

        # Joaco!, remove when the branding migration ...
        default_chart_css = '.chartBox .chartTitle a:hover{background:#ccc !important;} .chartBox .chartTitle a:hover{border-color:#999 !important;} .chartBox .chartTitle a:hover{color:#fff !important;}'
        return HttpResponse(default_chart_css, content_type='text/css')
    except AttributeError:
        return HttpResponse('', content_type='text/css')
示例#10
0
文件: views.py 项目: PhiRequiem/datal
def index(request):
    """ list all dataviews """
    ds_dao = DataStreamDBDAO()
    filters = ds_dao.query_filters(account_id=request.user.account.id,
                                    language=request.user.language)

    return render_to_response('manageDataviews/index.html', locals())
示例#11
0
文件: views.py 项目: Junar/datal
def do_search(request, category_filters=None, datasets=None):
    account = request.account
    preferences = request.preferences
    form = forms.SearchForm(request.GET)

    if form.is_valid():
        query = form.get_query()
        page = form.cleaned_data.get('page')
        order = form.cleaned_data.get('order')

        featured_accounts = account.account_set.values('id').all()
        if featured_accounts:
            accounts_ids = [featured_account['id'] for featured_account in featured_accounts]
        else:
            accounts_ids = account.id

        try:
            resources = ["ds", "db", "vz", "dt"]
            results, search_time, facets = FinderManager().search(
                query=query, account_id=accounts_ids, category_filters=category_filters, order=order,
                resource=resources
            )
        except InvalidPage:
            raise InvalidPage


        paginator = Paginator(results, settings.PAGINATION_RESULTS_PER_PAGE)
        page_results = paginator.page(page).object_list

        return render_to_response('search/search.html', locals())
    else:
        raise Http404
示例#12
0
文件: views.py 项目: anukat2015/datal
def edit_branding(request):
    account = request.auth_manager.get_account()
    preferences = account.get_preferences()
    keys = [
        'account.page.titles', 
        'account.header.uri', 
        'account.header.height', 
        'account.footer.uri', 
        'account.footer.height', 
        'account.favicon',
        'account.title.color', 
        'account.button.bg.color', 
        'account.button.border.color', 
        'account.button.font.color', 
        'account.mouseover.bg.color', 
        'account.mouseover.border.color', 
        'account.mouseover.title.color', 
        'account.mouseover.text.color', 
        'account.header.bg.color', 
        'account.header.border.color',
        'account.logo'
    ]

    form = forms.AccountBrandingForm(initial=get_initial(account, keys))
    updateCache = random.random()
    branding = True
    return render_to_response('admin_manager/branding.html', locals())
示例#13
0
文件: views.py 项目: anukat2015/datal
def edit_social(request):
    account = request.auth_manager.get_account()
    preferences = account.get_preferences()
    keys = ['account.comments', 'enable.embed.options', 'account.enable.sharing', 'account.enable.notes', 'account.dataset.download']
    form = forms.AccountSocialForm(initial=get_initial(account, keys))
    social = True
    return render_to_response('admin_manager/social.html', locals())
示例#14
0
文件: views.py 项目: anukat2015/datal
def view(request, dataset_id, slug):
    """ Show dataset """
    account = request.account
    preferences = request.preferences

    dataset = DatasetDBDAO().get(request.user, dataset_id=dataset_id, published=True)

    return render_to_response('viewDataset/index.html', locals())
示例#15
0
文件: views.py 项目: PhiRequiem/datal
def index(request):
    """ List all Datasets """
    account_domain = request.preferences["account.domain"]
    ds_dao = DatasetDBDAO()
    filters = ds_dao.query_filters(account_id=request.user.account.id, language=request.user.language)
    datastream_impl_valid_choices = DATASTREAM_IMPL_VALID_CHOICES

    return render_to_response("manageDatasets/index.html", locals())
示例#16
0
文件: views.py 项目: PhiRequiem/datal
def action_view(request, revision_id):

    visualization_revision = VisualizationDBDAO().get(
        request.auth_manager.language,
        visualization_revision_id=revision_id
    )

    return render_to_response('viewVisualization/index.html', locals())
示例#17
0
文件: views.py 项目: Junar/datal
def load(request):
    """
    Shows the microsite's home page
    :param request:
    """
    jsonObject = None
    language = request.auth_manager.language
    account = request.account
    preferences = request.preferences
    is_preview = 'preview' in request.GET and request.GET['preview'] == 'true'
    if is_preview or preferences["account_home"]:
        """ shows the home page new version"""
        if is_preview:
            jsonObject = json.loads(preferences["account_preview"], strict=False)
        elif preferences["account_has_home"]:
            jsonObject = json.loads(preferences["account_home"], strict=False)

        if jsonObject:
            themeid = jsonObject['theme']
            config = jsonObject['config']
            datastreams = []
            resources = []
            if config:
                if 'sliderSection' in config:
                    datastreams = retrieveDatastreams(config['sliderSection'], language)
                if 'linkSection' in config:
                    resources = retrieveResourcePermalinks(config['linkSection'], language)

            if preferences['account_home_filters'] == 'featured_accounts': # the account have federated accounts (childs)
                featured_accounts = Account.objects.get_featured_accounts(account.id)
                account_id = [featured_account['id'] for featured_account in featured_accounts]
                for index, f in enumerate(featured_accounts):
                    featured_accounts[index]['link'] = Account.objects.get(id=f['id']).get_preference('account.domain')

                categories = Category.objects.get_for_home(language, account_id)
            else:
                account_id = account.id
                categories = Category.objects.get_for_home(language, account_id)

            queryset = FinderQuerySet(FinderManager(HomeFinder), max_results=250, account_id=account_id )
            

            paginator = Paginator(queryset, 25)
            revisions = paginator.page(1)

            if preferences['account_home_filters'] == 'featured_accounts':
                add_domains_to_permalinks(revisions.object_list)

            return render_to_response('loadHome/home_'+themeid+'.html', locals())
        else:
            # No Home, return to featured Dashboards
            # return redirect('/dashboards/')

            # For the moment, redirect to search
            return redirect('/search/')
    else:
        # For the moment, redirect to search, but this needs to be erased
        return redirect('/search/')
示例#18
0
文件: views.py 项目: anukat2015/datal
def index_users(request):
    auth_manager = request.auth_manager
    preferences = auth_manager.get_account().get_preferences()
    roles = AccountRoles.ALL
    form = forms.UserForm(roles)
    users = User.objects.values('id', 'name', 'nick', 'last_visit', 'email', 'roles__name', 'roles__code').filter(
        account=auth_manager.account_id, roles__code__in=roles).all()
    users = [ user for user in users if user['roles__code'] in roles ]
    return render_to_response('admin_manager/users.html', locals())
示例#19
0
文件: views.py 项目: mxabierto/datal
def embed(request, guid):
    account = request.account
    preferences = request.preferences
    msprotocol = 'https' if account.get_preference('account.microsite.https') else 'http'
    base_uri = msprotocol + '://' + preferences['account_domain']

    try:
        datastream = DataStreamDBDAO().get(
            preferences['account_language'], guid=guid, published=True )
        parameters_query = RequestProcessor(request).get_arguments(datastream['parameters'])
    except Http404:
        return render_to_response('viewDataStream/embed404.html', {'settings': settings, 'request': request})

    DatastreamHitsDAO(datastream).add(ChannelTypes.WEB)
    end_point = urllib.urlencode(parameters_query)
    header_row = request.REQUEST.get('header_row', False)
    fixed_column = request.REQUEST.get('fixed_column', False)

    return render_to_response('viewDataStream/embed.html', locals())
示例#20
0
文件: views.py 项目: anukat2015/datal
def search(request, category=None):
    account = request.account
    preferences = request.preferences
    form = forms.SearchForm(request.GET)

    if form.is_valid():
        query = form.get_query()
        page = form.cleaned_data.get('page')
        order = form.cleaned_data.get('order')
        reverse = form.cleaned_data.get('reverse')
        resource = form.cleaned_data.get('resource')

        all_resources = ["dt", "ds", "vz"]
        all_resources.extend([finder.doc_type for finder in DatalPluginPoint.get_active_with_att('finder')])

        # si no se pasa resource o es cualquier cosa
        # utiliza el all_resources
        if not resource or resource not in all_resources:
            
            # en caso de que la preferencia este en False, se excluye el DT
            if not account.get_preference("account.dataset.show"):
                all_resources.remove("dt")
            resource=all_resources
        # no puede buscar por dt si account.dataset.show == False
        elif resource == "dt" and not account.get_preference("account.dataset.show"):
            raise InvalidPage

        try:
            meta_data= json.loads(form.cleaned_data.get('meta_data'))
        except ValueError:
            meta_data=None

        accounts_ids = [x['id'] for x in account.account_set.values('id').all()] + [account.id]

        results, search_time, facets = FinderManager().search(
            query=query, account_id=accounts_ids, category_filters=category, order=order,
            resource=resource, reverse=reverse, meta_data=meta_data
        )

        paginator = Paginator(results, settings.PAGINATION_RESULTS_PER_PAGE)

        try:
            page_results = paginator.page(page).object_list
        except EmptyPage:
            page_results = []

        pref_search_tips = preferences['account_search_tips']
        if pref_search_tips: 
            search_tips = json.loads(pref_search_tips)
        else:
            search_tips = {}

        return render_to_response('search/search.html', locals())
    else:
        raise Http404
示例#21
0
def edit_social(request):
    account = request.auth_manager.get_account()
    preferences = account.get_preferences()
    keys = [
        'account.comments', 'enable.embed.options', 'account.enable.sharing',
        'account.enable.notes', 'account.dataset.download',
        'account.dataset.show'
    ]
    form = forms.AccountSocialForm(initial=get_initial(account, keys))
    social = True
    return render_to_response('admin_manager/social.html', locals())
示例#22
0
文件: views.py 项目: PhiRequiem/datal
def create(request):
    auth_manager = request.auth_manager
    if request.method == 'POST':
        """ save new or update dataset """
        form = CreateDataStreamForm(request.POST)

        if not form.is_valid():
            raise DatastreamSaveException('Invalid form data: %s' % str(form.errors.as_text()))

        dataset_revision = DatasetRevision.objects.get(pk=form.cleaned_data['dataset_revision_id'])

        dataview = DatastreamLifeCycleManager(user=request.user)
        dataview.create(
            dataset=dataset_revision.dataset,
            language=request.auth_manager.language,
            category_id=form.cleaned_data['category'],
            parameters=[], #TODO: Add parameters to UI
            **form.cleaned_data
        )

        response = dict(
            status='ok',
            datastream_revision_id=dataview.datastream_revision.id,
            messages=[ugettext('APP-DATASET-CREATEDSUCCESSFULLY-TEXT')]
        )

        return JSONHttpResponse(json.dumps(response))

    elif request.method == 'GET':
        form = InitalizeCollectForm(request.GET)

        if form.is_valid():
            is_update = False
            is_update_selection = False
            data_set_id = form.cleaned_data['dataset_revision_id']
            datastream_id = None

            if auth_manager.is_level('level_5'):
                meta_data = Account.objects.get(pk=auth_manager.account_id).meta_data

            try:
                dataset_revision = DatasetRevision.objects.get(pk= data_set_id)
            except DatasetRevision.DoesNotExist:
                raise DatasetNotFoundException()

            end_point = dataset_revision.end_point
            type = dataset_revision.dataset.type
            impl_type = dataset_revision.impl_type
            impl_details = dataset_revision.impl_details
            bucket_name = request.bucket_name

            return render_to_response('view_manager/insertForm.html', locals())
        else:
            raise Http404
示例#23
0
文件: views.py 项目: mxabierto/datal
def my_account(request):
    user = User.objects.get(pk=request.auth_manager.id)
    if request.method == "GET":
        form = forms.MyAccountForm(instance=user)
        return render_to_response("accounts/my_account.html", locals())

    elif request.method == "POST":
        form = forms.MyAccountForm(request.POST, instance=user)
        if form.is_valid():
            user = form.save()
            new_password = form.cleaned_data.get("new_password")
            if new_password:
                user.password = new_password
                user.save()

            messages.add_message(request, messages.INFO, ugettext("ACCOUNT-SAVE-SUCCESS"))
            return render_to_response("accounts/my_account.html", locals())

        else:
            return render_to_response("accounts/my_account.html", locals())
示例#24
0
文件: views.py 项目: anukat2015/datal
def view(request, revision_id):

    try:
        visualization_revision = VisualizationDBDAO().get(request.user,
            visualization_revision_id=revision_id
        )
    except VisualizationRevision.DoesNotExist:
        logger.info("VisualizationRevision ID %s does not exist" % revision_id)
        raise VisualizationNotFoundException()

    return render_to_response('viewVisualization/index.html', locals())
示例#25
0
def my_account(request):
    user = User.objects.get(pk=request.auth_manager.id)
    if request.method == 'GET':
        form = forms.MyAccountForm(instance = user)
        return render_to_response('accounts/my_account.html', locals())

    elif request.method == 'POST':
        form = forms.MyAccountForm(request.POST, instance=user)
        if form.is_valid():
            user = form.save()
            new_password = form.cleaned_data.get('new_password')
            if new_password:
                user.password = new_password
                user.save()

            messages.add_message(request, messages.INFO, ugettext('ACCOUNT-SAVE-SUCCESS'))
            return render_to_response('accounts/my_account.html', locals())

        else:
            return render_to_response('accounts/my_account.html', locals())
示例#26
0
def index_users(request):
    auth_manager = request.auth_manager
    preferences = auth_manager.get_account().get_preferences()
    roles = AccountRoles.ALL
    form = forms.UserForm(roles)
    users = User.objects.values('id', 'name', 'nick', 'last_visit', 'email',
                                'roles__name', 'roles__code').filter(
                                    account=auth_manager.account_id,
                                    roles__code__in=roles).all()
    users = [user for user in users if user['roles__code'] in roles]
    return render_to_response('admin_manager/users.html', locals())
示例#27
0
def index(request):
    """ List all Datasets
    :param request:
    """
    account_domain = request.preferences['account.domain']
    ds_dao = DatasetDBDAO()
    filters = ds_dao.query_filters(account_id=request.user.account.id,
                                   language=request.user.language)
    datastream_impl_valid_choices = DATASTREAM_IMPL_VALID_CHOICES

    return render_to_response('manageDatasets/index.html', locals())
示例#28
0
def create(request, collect_type='index'):

    auth_manager = request.auth_manager
    account_id = auth_manager.account_id
    language = auth_manager.language
    extensions_list = SOURCE_EXTENSION_LIST

    collect_type_id = next(x[1] for x in COLLECT_TYPE_SLUGS
                           if x[0] == collect_type)

    default_category = request.account.get_preference(
        'account.default.category') or None
    initial = None
    if default_category:
        try:
            initial = {'category': int(default_category)}
        except ValueError:
            pass

    if request.method == 'GET':
        form = DatasetFormFactory(collect_type_id).create(
            account_id=account_id,
            language=language,
            status_choices=auth_manager.get_allowed_actions(),
            initial=initial)
        form.label_suffix = ''
        url = 'createDataset/{0}.html'.format(collect_type)
        return render_to_response(url, locals())

    elif request.method == 'POST':
        """update dataset """
        form = DatasetFormFactory(collect_type_id).create(
            request,
            account_id=account_id,
            language=language,
            status_choices=auth_manager.get_allowed_actions())

        if form.is_valid():
            lifecycle = DatasetLifeCycleManager(user=request.user)
            dataset_revision = lifecycle.create(
                collect_type=request.POST.get('collect_type'),
                language=language,
                account_id=account_id,
                **form.cleaned_data)

            # TODO: Create a CreateDatasetResponse object
            data = dict(
                status='ok',
                messages=[ugettext('APP-DATASET-CREATEDSUCCESSFULLY-TEXT')],
                dataset_revision_id=dataset_revision.id)
            return HttpResponse(json.dumps(data), content_type='text/plain')
        else:
            raise DatasetSaveException(form)
示例#29
0
def edit_info(request):
    account = request.auth_manager.get_account()
    keys = [
        'account.name', 'account.link', 'account.contact.person.name',
        'account.contact.person.email', 'account.contact.person.phone',
        'account.contact.person.country', 'account.contact.dataperson.email',
        'account.timezone'
    ]

    form = forms.AccountInfoForm(initial=get_initial(account, keys))
    account_info = True
    return render_to_response('admin_manager/info.html', locals())
示例#30
0
def create(request):
    auth_manager = request.auth_manager
    if request.method == 'POST':
        """ save new or update dataset """
        form = CreateDataStreamForm(request.POST)

        if not form.is_valid():
            raise DatastreamSaveException('Invalid form data: %s' % str(form.errors.as_text()))

        dataset_revision = DatasetRevision.objects.get(pk=form.cleaned_data['dataset_revision_id'])

        dataview = DatastreamLifeCycleManager(user=request.user)
        dataview.create(
            dataset=dataset_revision.dataset,
            language=request.auth_manager.language,
            category_id=form.cleaned_data['category'],
            **form.cleaned_data
        )

        response = dict(
            status='ok',
            datastream_revision_id=dataview.datastream_revision.id,
            messages=[ugettext('APP-DATASET-CREATEDSUCCESSFULLY-TEXT')]
        )

        return JSONHttpResponse(json.dumps(response))

    elif request.method == 'GET':
        form = InitalizeCollectForm(request.GET)

        if form.is_valid():
            is_update = False
            is_update_selection = False
            data_set_id = form.cleaned_data['dataset_revision_id']
            datastream_id = None

            if auth_manager.is_level('level_5'):
                meta_data = Account.objects.get(pk=auth_manager.account_id).meta_data

            try:
                dataset_revision = DatasetRevision.objects.get(pk=data_set_id)
            except DatasetRevision.DoesNotExist:
                raise DatasetNotFoundException()

            end_point = dataset_revision.end_point
            type = dataset_revision.dataset.type
            impl_type = dataset_revision.impl_type
            impl_details = dataset_revision.impl_details
            bucket_name = request.bucket_name

            return render_to_response('view_manager/insertForm.html', locals())
        else:
            raise Http404
示例#31
0
文件: views.py 项目: mxabierto/datal
def view(request, revision_id):

    try:
        visualization_revision = VisualizationDBDAO().get(
            request.auth_manager.language,
            visualization_revision_id=revision_id
        )
    except VisualizationRevision.DoesNotExist:
        logger.info("VisualizationRevision ID %s does not exist" % revision_id)
        raise VisualizationNotFoundException()

    return render_to_response('viewVisualization/index.html', locals())
示例#32
0
文件: views.py 项目: PhiRequiem/datal
def action_view(request, revision_id):
    account_id = request.auth_manager.account_id
    credentials = request.auth_manager
    user_id = request.auth_manager.id
    language = request.auth_manager.language
    try:
        dataset = DatasetDBDAO().get(language=language, dataset_revision_id=revision_id)
    except DatasetRevision.DoesNotExist:
        raise DatasetNotFoundException()

    datastream_impl_not_valid_choices = DATASTREAM_IMPL_NOT_VALID_CHOICES
    return render_to_response("viewDataset/index.html", locals())
示例#33
0
文件: views.py 项目: PhiRequiem/datal
def action_embed(request, guid):
    account = request.account
    preferences = request.preferences
    base_uri = 'http://' + preferences['account_domain']

    try:
        datastreamrevision_id = DataStreamRevision.objects.get_last_published_by_guid(guid)
        datastream = DataStreamDBDAO().get(
            preferences['account_language'],
            datastream_revision_id=datastreamrevision_id
        )
        parameters_query = RequestProcessor(request).get_arguments(datastream.parameters)
    except Http404:
        return render_to_response('datastream_manager/embed404.html', {'settings': settings, 'request': request})

    DatastreamHitsDAO(datastream).add(ChannelTypes.WEB)
    end_point = urllib.urlencode(parameters_query)
    header_row = request.REQUEST.get('header_row', False)
    fixed_column = request.REQUEST.get('fixed_column', False)

    return render_to_response('datastream_manager/embed.html', locals())
示例#34
0
文件: views.py 项目: jnaudon/datal
def sitemap(request):

    language = request.auth_manager.language
    account = request.account
    params = request.GET

    domain = get_domain_by_request(request)
    now = now()
    dss = DataStreamDBDAO().query(account_id=account.id, language=language, filters_dict=dict(status=[3]))[0]
    vss = VisualizationDBDAO().query(account_id=account.id, language=language, filters_dict=dict(status=[3]))[0]

    return render_to_response('sitemap.xml', locals(), content_type="application/xml")
示例#35
0
文件: views.py 项目: anukat2015/datal
def browse(request, category_slug=None, page=1):
    account = request.account
    preferences = request.preferences

    category = Category.objects.get_for_browse(category_slug, account.id, preferences['account_language'])
    accounts_ids =  [x['id'] for x in account.account_set.values('id').all()] + [account.id]

    results, search_time, facets = FinderManager().search(category_id=category['id'], account_id=[account.id]+accounts_ids)

    paginator = Paginator(results, settings.PAGINATION_RESULTS_PER_PAGE)
    page_results = paginator.page(page).object_list

    return render_to_response('search/search.html', locals())
示例#36
0
def browse(request, category_slug=None, page=1):
    account = request.account
    preferences = request.preferences

    category = Category.objects.get_for_browse(category_slug, account.id, preferences['account_language'])
    accounts_ids =  [x['id'] for x in account.account_set.values('id').all()] + [account.id]

    results, search_time, facets = FinderManager().search(category_id=category['id'], account_id=[account.id]+accounts_ids)

    paginator = Paginator(results, settings.PAGINATION_RESULTS_PER_PAGE)
    page_results = paginator.page(page).object_list

    return render_to_response('search/search.html', locals())
示例#37
0
def embed(request, guid):
    account = request.account
    preferences = request.preferences
    msprotocol = 'https' if account.get_preference('account.microsite.https') else 'http'
    base_uri = msprotocol + '://' + preferences['account_domain']

    try:
        # parche horrible para usar account_language en vez del language del user
        user = request.user
        user.language=preferences['account_language']

        datastream = DataStreamDBDAO().get(user, guid=guid, published=True )
        parameters_query = RequestProcessor(request).get_arguments(datastream['parameters'])
    except DataStreamRevision.DoesNotExist:
        return render_to_response('viewDataStream/embed404.html', {'settings': settings, 'request': request})

    DatastreamHitsDAO(datastream).add(ChannelTypes.WEB)
    end_point = urllib.urlencode(parameters_query)
    header_row = request.REQUEST.get('header_row', False)
    fixed_column = request.REQUEST.get('fixed_column', False)

    return render_to_response('viewDataStream/embed.html', locals())
示例#38
0
文件: views.py 项目: mxabierto/datal
def sitemap(request):
    import datetime

    language = request.auth_manager.language
    account = request.account
    params = request.GET

    domain = get_domain_by_request(request)
    now = datetime.datetime.now()
    dss = DataStreamDBDAO().query(account_id=account.id, language=language, filters_dict=dict(status=[3]))
    vss = VisualizationDBDAO().query(account_id=account.id, language=language, filters_dict=dict(status=[3]))

    return render_to_response('sitemap.xml', locals(), mimetype="application/xml")
示例#39
0
文件: views.py 项目: anukat2015/datal
def view(request, revision_id):

    account_id = request.auth_manager.account_id
    credentials = request.auth_manager
    user_id = request.auth_manager.id
    language = request.auth_manager.language
    try:
        dataset = DatasetDBDAO().get(user=request.user, dataset_revision_id=revision_id)
    except DatasetRevision.DoesNotExist:
        raise DatasetNotFoundException()

    datastream_impl_not_valid_choices = DATASTREAM_IMPL_NOT_VALID_CHOICES
    return render_to_response('viewDataset/index.html', locals())
示例#40
0
文件: views.py 项目: PhiRequiem/datal
def index(request):
    """ list all dataviews """
    dao = VisualizationDBDAO()

    resources, total_resources = dao.query(account_id=request.account.id, language=request.user.language)

    for resource in resources:
        resource['url'] = reverse('manageVisualizations.view', urlconf='workspace.urls', kwargs={'revision_id': resource['id']})

    filters = dao.query_filters(account_id=request.user.account.id,
                                    language=request.user.language)

    return render_to_response('manageVisualizations/index.html', locals())
示例#41
0
文件: views.py 项目: PhiRequiem/datal
def action_embed(request, guid):

    account     = request.account
    preferences = request.preferences
    base_uri = 'http://' + preferences['account_domain']

    try:
        visualizationrevision_id = VisualizationRevision.objects.get_last_published_by_guid(guid)
        visualization_revision = VZ(visualizationrevision_id, preferences['account_language'])
    except:
        return render_to_response('chart_manager/embed404.html',{'settings': settings, 'request' : request})

    VisualizationHitsDAO(visualization_revision.visualization).add(ChannelTypes.WEB)
    width     = request.REQUEST.get('width', False)
    height    = request.REQUEST.get('height', False)

    visualization_revision_parameters = RequestProcessor(request).get_arguments(visualization_revision.parameters)
    visualization_revision_parameters['pId'] = visualization_revision.datastreamrevision_id
    json, type = invoke(visualization_revision_parameters)
    visualization_revision_parameters = urllib.urlencode(visualization_revision_parameters)

    return render_to_response('chart_manager/embed.html', locals())
示例#42
0
文件: views.py 项目: Junar/datal
def view(request, revision_id):
    language = request.auth_manager.language
    try:
        datastream = DataStreamDBDAO().get(language, datastream_revision_id=revision_id)
    except DataStreamRevision.DoesNotExist:
        raise DataStreamNotFoundException()

    account_id = request.auth_manager.account_id
    credentials = request.auth_manager
    categories = CategoryI18n.objects.filter(language=language, category__account=account_id).values('category__id',
                                                                                                     'name')
    status_options = credentials.get_allowed_actions()

    return render_to_response('viewDataStream/index.html', locals())
示例#43
0
def view(request, revision_id):
    language = request.auth_manager.language
    try:
        datastream = DataStreamDBDAO().get(language, datastream_revision_id=revision_id)
    except DataStreamRevision.DoesNotExist:
        raise DataStreamNotFoundException()

    account_id = request.auth_manager.account_id
    credentials = request.auth_manager
    categories = CategoryI18n.objects.filter(language=language, category__account=account_id).values('category__id',
                                                                                                     'name')
    status_options = credentials.get_allowed_actions()

    return render_to_response('viewDataStream/index.html', locals())
示例#44
0
def load(request):
    """
    Shows the microsite's home page
    :param request:
    """
    jsonObject = None
    language = request.auth_manager.language
    account = request.account
    preferences = request.preferences
    is_preview = 'preview' in request.GET and request.GET['preview'] == 'true'

    
    builder = ThemeBuilder(preferences, is_preview, language, account)

    if is_preview or preferences["account_home"]:
        """ shows the home page new version"""
        data = builder.parse()

        if data:

            accounts_ids=data['federated_accounts_ids'] + [account.id]

            queryset = FinderQuerySet(FinderManager(HomeFinder), 
                max_results=250, account_id=accounts_ids )

            paginator = Paginator(queryset, 25)
            revisions = paginator.page(1)

            if data['federated_accounts_ids']:
                add_domains_to_permalinks(revisions.object_list)

            context = data.copy()
            context['has_federated_accounts'] = data['federated_accounts_ids'] != []
            context['request'] = request
            context['paginator'] = paginator
            context['revisions'] = revisions
            context['categories'] = Category.objects.get_for_home(language, accounts_ids)

            context['categories_dict'] = {}
            for cat in context['categories']:
                key = str(cat['id'])
                context['categories_dict'][key] = cat['name']

            return render_to_response(data['template_path'], context)
        else:
            # For the moment, redirect to search
            return redirect('/search/')
    else:
        # For the moment, redirect to search, but this needs to be erased
        return redirect('/search/')
示例#45
0
文件: views.py 项目: anukat2015/datal
def index(request):
    """ list all dataviews
    :param request:
    """
    dao = VisualizationDBDAO()

    resources, total_resources = dao.query(account_id=request.account.id, language=request.user.language)

    for resource in resources:
        resource['url'] = reverse('manageVisualizations.view', urlconf='workspace.urls', kwargs={'revision_id': resource['id']})

    filters = dao.query_filters(account_id=request.user.account.id,
                                    language=request.user.language)

    return render_to_response('manageVisualizations/index.html', locals())
示例#46
0
文件: views.py 项目: asanchez75/datal
def get_catalog_xml(request):
    logger = logging.getLogger(__name__)

    account_id = request.account.id
    language = request.auth_manager.language
    preferences = request.preferences
    account = request.account
    
    domain = get_domain_by_request(request)
    api_domain = preferences['account_api_domain']
    transparency_domain = preferences['account_api_transparency']
    account = Account.objects.get(pk=account_id)
    msprotocol = 'https' if account.get_preference('account.microsite.https') else 'http'
    apiprotocol = 'https' if account.get_preference('account.api.https') else 'http'
    developers_link = msprotocol + '://' + domain + reverse('manageDeveloper.filter')

    datastreams_revision_ids = DataStream.objects.values_list('last_published_revision').filter(last_published_revision__status=StatusChoices.PUBLISHED,
                user__account_id=account_id)

    # necesario, porque el DAO.get requiere un usuario para obtener el language y el account
    user = AccountAnonymousUser(account, request.auth_manager.language)

    resources = []
    for datastream_revision_id, in datastreams_revision_ids:
        ds = DataStreamDBDAO().get(user, datastream_revision_id=datastream_revision_id, published=True)
        permalink = reverse('viewDataStream.view', urlconf='microsites.urls', kwargs={'id': ds['resource_id'], 'slug': ds['slug']}) 
        ds['link'] = '{}://{}{}'.format(msprotocol, domain, permalink)
        ds['export_csv_link'] = '{}://{}{}'.format(msprotocol, domain,reverse('datastreams-data', kwargs={'id': ds['resource_id'],'format':'csv'}))
        ds['export_html_link'] = '{}://{}{}'.format(msprotocol, domain, reverse('datastreams-data', kwargs={'id': ds['resource_id'], 'format': 'html'}) )
        ds['api_link'] = apiprotocol + '://' + api_domain + '/datastreams/' + ds['guid'] + '/data/?auth_key=your_authkey'

        ds['visualizations'] = []
        visualization_revision_ids = Visualization.objects.values_list('last_published_revision').filter(
            datastream_id=ds['resource_id'],
            last_published_revision__status=StatusChoices.PUBLISHED
        )

        for visualization_revision_id, in visualization_revision_ids:
            vz = VisualizationDBDAO().get(user, visualization_revision_id=visualization_revision_id, published=True)
            permalink = reverse('chart_manager.view', urlconf='microsites.urls', kwargs={'id': vz['resource_id'], 'slug': vz['slug']})
            vz['link'] = msprotocol + '://' + domain + permalink
            ds['visualizations'].append(vz)
        resources.append(ds)

    return render_to_response('catalog.xml', locals(), content_type='application/xml')
示例#47
0
def edit_branding(request):
    account = request.auth_manager.get_account()
    preferences = account.get_preferences()
    keys = [
        'account.page.titles', 'account.header.uri', 'account.header.height',
        'account.footer.uri', 'account.footer.height', 'account.favicon',
        'account.title.color', 'account.button.bg.color',
        'account.button.border.color', 'account.button.font.color',
        'account.mouseover.bg.color', 'account.mouseover.border.color',
        'account.mouseover.title.color', 'account.mouseover.text.color',
        'account.header.bg.color', 'account.header.border.color',
        'account.logo'
    ]

    form = forms.AccountBrandingForm(initial=get_initial(account, keys))
    updateCache = random.random()
    branding = True
    return render_to_response('admin_manager/branding.html', locals())
示例#48
0
def create(request, collect_type='index'):

    auth_manager = request.auth_manager
    account_id = auth_manager.account_id
    language = auth_manager.language
    extensions_list = SOURCE_EXTENSION_LIST

    # TODO: Put line in a common place
    collect_types = {'index': -1, 'file': 0, 'url': 1, 'webservice': 2}

    collect_type_id = collect_types[collect_type]

    if request.method == 'GET':
        form = DatasetFormFactory(collect_type_id).create(
            account_id=account_id,
            language=language,
            status_choices=auth_manager.get_allowed_actions())
        form.label_suffix = ''
        url = 'createDataset/{0}.html'.format(collect_type)
        return render_to_response(url, locals())

    elif request.method == 'POST':
        """update dataset """
        form = DatasetFormFactory(collect_type_id).create(
            request,
            account_id=account_id,
            language=language,
            status_choices=auth_manager.get_allowed_actions())

        if form.is_valid():
            lifecycle = DatasetLifeCycleManager(user=request.user)
            dataset_revision = lifecycle.create(
                collect_type=request.POST.get('collect_type'),
                language=language,
                **form.cleaned_data)

            # TODO: Create a CreateDatasetResponse object
            data = dict(
                status='ok',
                messages=[ugettext('APP-DATASET-CREATEDSUCCESSFULLY-TEXT')],
                dataset_revision_id=dataset_revision.id)
            return HttpResponse(json.dumps(data), content_type='text/plain')
        else:
            raise DatasetSaveException(form)
示例#49
0
文件: views.py 项目: anukat2015/datal
def view(request, id, slug=None):
    """
    Show a microsite view
    """
    account = request.account

    preferences = request.preferences

    try:
        visualization_revision = VisualizationDBDAO().get(request.user,
                                                          visualization_id=id,
                                                          published=True)

        visualization = visualization_revision['visualization']

        #for datastream sidebar functions (downloads and others)
        datastream = DataStreamDBDAO().get(
            request.user,
            datastream_revision_id=visualization_revision[
                "datastream_revision_id"])

    except VisualizationRevision.DoesNotExist:
        raise VisualizationRevisionDoesNotExist
    else:
        VisualizationHitsDAO(visualization_revision).add(ChannelTypes.WEB)

        visualization_revision_parameters = RequestProcessor(
            request).get_arguments(visualization_revision["parameters"])

        chart_type = json.loads(
            visualization_revision["impl_details"]).get('format').get('type')
        if chart_type == 'mapchart':
            geo_type = json.loads(visualization_revision["impl_details"]).get(
                'chart').get('geoType')
        else:
            geo_type = ''

        visualization_revision_parameters = urllib.urlencode(
            visualization_revision_parameters)

        notes = visualization_revision['notes']

        return render_to_response('viewChart/index.html', locals())
示例#50
0
def view(request, id, slug):
    logger = logging.getLogger(__name__)

    account = request.account

    preferences = request.preferences

    datastream = DataStreamDBDAO().get(
        language=preferences['account_language'],
        datastream_id=id,
        published=True)

    url_query = urllib.urlencode(
        RequestProcessor(request).get_arguments(datastream['parameters']))

    DatastreamHitsDAO(datastream).add(ChannelTypes.WEB)

    notes = datastream['notes']

    return render_to_response('viewDataStream/index.html', locals())
示例#51
0
def edit_domain(request):
    default_domain = '.' + settings.DOMAINS['microsites']
    account = request.auth_manager.get_account()
    preferences = account.get_preferences()
    keys = [
        'account.domain', 'account.api.domain', 'account.transparency.domain'
    ]

    initial = get_initial(account, keys)

    if initial['account_domain'].endswith(default_domain):
        initial['pick_a_domain'] = 'internal'
        initial['account_domain_internal'] = initial['account_domain'].replace(
            default_domain, '')
    else:
        initial['pick_a_domain'] = 'external'
        initial['account_domain_external'] = initial['account_domain']

    form = forms.AccountDomainForm(initial)
    return render_to_response('admin_manager/domain.html', locals())
示例#52
0
def update_categories(request):
    language = request.auth_manager.language
    params = request.GET
    account_id = params.get('account_id','')

    # we need a full categories list in case is a "federated account" (have childs accounts)
    if account_id == '':
        account = request.account
        preferences = request.preferences
        builder = ThemeBuilder(preferences, False, language, account)
        data = builder.parse()

        if data['federated_accounts_ids']:
            federated_accounts=data['federated_accounts']
    
        categories = data['categories']
    else:
        # account_id is single account or a list of federated accounts
        categories = Category.objects.get_for_home(language, account_id)

    return render_to_response('loadHome/categories.js', locals(), mimetype="text/javascript")
示例#53
0
def index_categories(request):
    logger = logging.getLogger(__name__)
    auth_manager = request.auth_manager
    account = auth_manager.get_account()
    preferences = account.get_preferences()
    form = forms.CategoryEditForm()
    categories = Category.objects.values(
        'id', 'categoryi18n__name', 'categoryi18n__description').filter(
            account=auth_manager.account_id,
            categoryi18n__language=auth_manager.language)
    categories_tab = True

    # for block the "delete" button on transparency categories
    used_transparency_categories = preferences[
        'account.transparency.categories'].split()

    try:
        default_category = int(preferences['account.default.category'])
    except:
        default_category = None
    return render_to_response('admin_manager/categories.html', locals())
示例#54
0
def do_search(request, category_filters=None, datasets=None):

    account = request.account
    preferences = request.preferences
    form = forms.SearchForm(request.GET)

    if form.is_valid():
        query = form.get_query()
        page = form.cleaned_data.get('page')
        order = form.cleaned_data.get('order')
        reverse = form.cleaned_data.get('reverse')

        accounts_ids = [
            x['id'] for x in account.account_set.values('id').all()
        ] + [account.id]

        try:
            resources = ["ds", "db", "vz", "dt"]
            results, search_time, facets = FinderManager().search(
                query=query,
                account_id=accounts_ids,
                category_filters=category_filters,
                order=order,
                resource=resources,
                reverse=reverse)
        except InvalidPage:
            raise InvalidPage

        paginator = Paginator(results, settings.PAGINATION_RESULTS_PER_PAGE)
        page_results = paginator.page(page).object_list

        pref_search_tips = preferences['account_search_tips']
        if pref_search_tips:
            search_tips = json.loads(pref_search_tips)
        else:
            search_tips = {}

        return render_to_response('search/search.html', locals())
    else:
        raise Http404
示例#55
0
def view(request, id, slug=None):
    """
    Show a microsite view
    """
    account = request.account

    preferences = request.preferences

    try:
        visualization_revision = VisualizationDBDAO().get(
            preferences['account_language'],
            visualization_id=id,
            published=True
        )

        # verify if this account is the owner of this viz
        visualization = Visualization.objects.get(pk=id)
        if account.id != visualization.user.account.id:
            raise NotAccesVisualization

        #for datastream sidebar functions (downloads and others)
        datastream = DataStreamDBDAO().get(
            preferences['account_language'],
            datastream_revision_id=visualization_revision["datastream_revision_id"]
        )
        
    except VisualizationRevision.DoesNotExist:
        raise VisualizationRevisionDoesNotExist
    else:
        VisualizationHitsDAO(visualization_revision).add(ChannelTypes.WEB)

        visualization_revision_parameters = RequestProcessor(request).get_arguments(visualization_revision["parameters"])

        chart_type = json.loads(visualization_revision["impl_details"]).get('format').get('type')

        visualization_revision_parameters = urllib.urlencode(visualization_revision_parameters)

        notes = visualization_revision['notes']

        return render_to_response('viewChart/index.html', locals())
示例#56
0
文件: views.py 项目: asanchez75/datal
def create(request):
    """

    :param request:
    :return:
    """
    if request.method == 'GET':
        datastream_revision_id = request.GET.get('datastream_revision_id',
                                                 None)
        try:
            datastream_rev = DataStreamDBDAO().get(
                request.user,
                datastream_revision_id=datastream_revision_id,
                published=False)
        except DataStreamRevision.DoesNotExist:
            raise DataStreamNotFoundException()

        return render_to_response(
            'createVisualization/index.html',
            dict(request=request, datastream_revision=datastream_rev))

    elif request.method == 'POST':
        """ save new or update dataset """
        # Valido que llegue el ID de la revision del datastream
        datastream_rev_id = request.GET.get('datastream_revision_id', None)

        if not datastream_rev_id:
            raise Http404
        datastream_rev = DataStreamRevision.objects.get(pk=datastream_rev_id)

        form = VisualizationForm(request.POST)

        if not form.is_valid():
            raise VisualizationSaveException('Invalid form data: %s' %
                                             str(form.errors.as_text()))

        response = form.save(request, datastream_rev=datastream_rev)

        return JSONHttpResponse(json.dumps(response))
示例#57
0
文件: views.py 项目: asanchez75/datal
def edit(request, revision_id=None):
    if request.method == 'GET':
        visualization_rev = VisualizationDBDAO().get(
            request.user,
            visualization_revision_id=revision_id,
            published=False)

        datastream_rev = DataStreamDBDAO().get(
            request.user,
            datastream_revision_id=visualization_rev['datastream_revision_id'],
            published=False)
        return render_to_response(
            'createVisualization/index.html',
            dict(request=request,
                 datastream_revision=datastream_rev,
                 visualization_revision=visualization_rev))

    elif request.method == 'POST':
        """ save new or update dataset """
        # Formulario
        form = VisualizationForm(request.POST)
        if not form.is_valid():
            logger.info(form.errors)
            raise VisualizationSaveException('Invalid form data: %s' %
                                             str(form.errors.as_text()))

        visualization_rev = VisualizationDBDAO().get(
            request.user, visualization_revision_id=revision_id)
        response = form.save(request, visualization_rev=visualization_rev)

        # Signal
        visualization_changed.send_robust(
            sender='edit_view',
            id=visualization_rev['visualization_id'],
            rev_id=visualization_rev['visualization_revision_id'])

        return JSONHttpResponse(json.dumps(response))
示例#58
0
def get_new_css(request, id):
    try:
        account = request.account
        preferences = account.get_preferences()
        keys = [
            'account.title.color', 'account.button.bg.color',
            'account.button.border.color', 'account.button.font.color',
            'account.mouseover.bg.color', 'account.mouseover.border.color',
            'account.mouseover.title.color', 'account.mouseover.text.color'
        ]
        keys_copy = list(keys)
        preferences.load(keys)

        for key in keys_copy:
            if preferences[key.replace('.', '_')]:
                return render_to_response('css_branding/branding.css',
                                          locals(),
                                          mimetype='text/css')

        # Joaco!, remove when the branding migration ...
        default_chart_css = '.chartBox .chartTitle a:hover{background:#ccc !important;} .chartBox .chartTitle a:hover{border-color:#999 !important;} .chartBox .chartTitle a:hover{color:#fff !important;}'
        return HttpResponse(default_chart_css, content_type='text/css')
    except AttributeError:
        return HttpResponse('', content_type='text/css')
示例#59
0
def recovery(request):
    try:
        uuid = request.REQUEST['id']
    except:
        raise Http404

    try:
        pass_ticket = UserPassTickets.objects.get(uuid=uuid, type='PASS')
    except:
        pass_ticket = ''

    if pass_ticket != '':
        new_pass = GeneratePassword()

        user = User.objects.get(pk=pass_ticket.user_id)
        user.password = hashlib.md5(new_pass).hexdigest()
        user.save()
        DjangoMailService().send_password_recovered_mail(user, new_pass)
        if not request.auth_manager.is_anonymous():
            request.session.clear()
    else:
        raise Http404

    return render_to_response('accounts/recovery.html', locals())
示例#60
0
def create(request):
    auth_manager = request.auth_manager
    if request.method == 'POST':
        """ save new or update dataset """
        form = CreateDataStreamForm(request.POST)

        if not form.is_valid():
            raise DatastreamSaveException(form)

        dataset_revision = DatasetRevision.objects.get(
            pk=form.cleaned_data['dataset_revision_id'])

        dataview = DatastreamLifeCycleManager(user=request.user)
        dataview.create(dataset=dataset_revision.dataset,
                        language=request.auth_manager.language,
                        category_id=form.cleaned_data['category'],
                        **form.cleaned_data)

        response = dict(
            status='ok',
            datastream_revision_id=dataview.datastream_revision.id,
            messages=[ugettext('APP-DATASET-CREATEDSUCCESSFULLY-TEXT')])

        return JSONHttpResponse(json.dumps(response))

    elif request.method == 'GET':
        form = InitalizeCollectForm(request.GET)

        if form.is_valid():
            is_update = False
            is_update_selection = False
            data_set_id = form.cleaned_data['dataset_revision_id']
            datastream_id = None

            if auth_manager.is_level('level_5'):
                meta_data = Account.objects.get(
                    pk=auth_manager.account_id).meta_data

            try:
                dataset_revision = DatasetRevision.objects.get(pk=data_set_id)
            except DatasetRevision.DoesNotExist:
                raise DatasetNotFoundException()

            end_point = dataset_revision.end_point
            type = dataset_revision.dataset.type
            impl_type = dataset_revision.impl_type
            impl_details = dataset_revision.impl_details
            bucket_name = request.bucket_name

            categoriesQuery = CategoryI18n.objects\
                                .filter(language=request.auth_manager.language,
                                        category__account=request.auth_manager.account_id)\
                                .values('category__id', 'name')
            categories = [[category['category__id'], category['name']]
                          for category in categoriesQuery]
            preferences = auth_manager.get_account().get_preferences()
            try:
                default_category = int(preferences['account.default.category'])
            except:
                default_category = categories[0][0]
            # Agregar categoria por defecto
            categories = map(lambda x: x + [int(x[0]) == default_category],
                             categories)

            sources = [source for source in dataset_revision.get_sources()]
            tags = [tag for tag in dataset_revision.get_tags()]

            return render_to_response('createDataview/index.html', locals())
        else:
            raise Http404