def locations(request):

    paginate = Paginate()
    users = User.all()

    c = {}
    c.update(csrf(request))
    page = {}
    page.update(message.get_flash_message(request))
    page.update(paginate.paginate(0, 1))
    c["page"] = page
    c["users"] = users
    return render_to_response('locations/index.jinja', c)
def users(request):
    if request.method == 'POST' and request.POST["_method"] == "NEW":
        from app_search.helpers.app_helper import AppHelper
        data = request.POST.copy()
        data['date_joined'] = datetime.date.today()
        data['is_active'] = True
        print("before")
        print(data)
        if 'password' not in data or 'password' in data and data['password'] == '':
            print("generate password")
            data['password'] = AppHelper.generate_password()

        print("@@@ password={0}".format(data['password']))
        uform = UserForm(data)
        pform = UserProfileForm(data)
        if uform.is_valid() and pform.is_valid():
            u = uform.save()
            p = pform.save(commit = False)
            p.user = u
            p.save()
            if user and p:
                message.flash(request, "登録に成功しました", "success")
                # TODO: passwordの通知方法
                return redirect('user', pk = user.id)
            else:
                message.flash(request, "登録に失敗しました", "danger")

        else:
            message.flash_with_errors(request, "入力エラーです。", uform.errors, pform.errors)

        # end of POST
        c = {}
        c.update(csrf(request))
        page = {}
        page.update(message.get_flash_message(request))
        page.update({'form': uform})
        c["page"] = page
        return render_to_response('users/new.jinja', c)

    paginate = Paginate()
    users = User.objects.all()

    c = {}
    c.update(csrf(request))
    page = {}
    page.update(message.get_flash_message(request))
    page.update(paginate.paginate(0, 1))
    c["page"] = page
    c["users"] = users
    return render_to_response('users/index.jinja', c)
def search_results(request):
    pp = pprint.PrettyPrinter()
    client = riak.RiakClient()
    bucket = client.bucket_type(settings.RIAK["STORE_BUCKET_TYPE"]).bucket(settings.RIAK["STORE_BUCKET"])

    params = request.GET

    solr_server_url = "http://localhost:8098"
    query_interface = "search/query/{0}".format(settings.RIAK["STORE_BUCKET_TYPE"])

    # 検索クエリの作成
    query_ss = []

    if 'q' not in params or ('q' in params and params['q'].strip() == ""):
        query_ss.append(("q","*:*"))
    else:
        query_ss.append(("q","{1}:{0} OR {2}:{0} OR {3}:{0}".format(params["q"].strip(), 'titles_ja', 'creators_ts', 'identifiers_ts')))

    PAGER_DEFAULT = 10
    START_PAGE_DEFAULT = 1
    SORT_DEFAULT = next(filter(lambda x:x['key'] == "ma", SolrHelper.SEARCH_RESULTS_SORT), None)['v']

    per_page = PAGER_DEFAULT
    current_page = START_PAGE_DEFAULT
    params_o1 = ""
    params_o2 = ""
    params_p = ""
    if 'o1' in params:
        params_o1 = params['o1']
        try:
            per_page = int(next(filter(lambda x:x['key'] == params_o1, SolrHelper.SEARCH_RESULTS_PAGES), PAGER_DEFAULT)['v'])
        except ValueError as e:
            pass

    sort_method = SORT_DEFAULT
    if 'o2' in params:
        params_o2 = params['o2']
        if type(params_o2) == "array":
            params_o2 = params_o2[0]
        if params_o2 == "ma":
            sort_method = next(filter(lambda x:x['key'] == params_o2, SolrHelper.SEARCH_RESULTS_SORT), SORT_DEFAULT)['v']
        else:
            sort_method = "{0},{1}"\
                    .format(next(filter(lambda x:x['key'] == params_o2, SolrHelper.SEARCH_RESULTS_SORT), SORT_DEFAULT)['v']
                                           , SORT_DEFAULT)

    if 'p' in params:
        try:
            current_page = int(params['p'])
            if current_page < 1:
                raise ValueError
            params_p = params['p']
        except ValueError as e:
            pass

    start_pos = per_page * (current_page - 1)

    # その他のオプション
    query_exts = [("wt","json"),
                  ('json.nl', 'arrmap'),
                  ('fl', '_yz_rk'),
                  ('rows', per_page),
                  ('sort', sort_method),
                  ('start', start_pos),
                 ]

    #
    querys = []
    querys.extend(query_ss)
    querys.extend(query_exts)

    search_url = "{0}/{1}?{2}".format(solr_server_url, query_interface, urllib.parse.urlencode(querys))
    print(search_url)

    enc = "UTF-8"

    sock = urllib.request.urlopen(search_url)
    results = json.loads(sock.read().decode(enc))
    sock.close()

    #print(results)
    manifestations = []
    result_count = 0
    if 'response' in results and results['response']['numFound'] and results['response']['numFound'] > 0:
        result_count = results['response']['numFound']

        for result in results['response']['docs']:
            m = bucket.get(result['_yz_rk'])
            if m and m.data:
                manifestations.append(m.data)
            else:
                print("warning: no document! key={0}".format(result['_yz_rk']))

    # ===

    paginate = Paginate()

    pageinfo = {"search_result_count": result_count,
                "q": params["q"],
                "o1": params_o1,
                "o2": params_o2,
                "p": params_p,
                "o1list": SolrHelper.SEARCH_RESULTS_PAGES,
                "o2list": SolrHelper.SEARCH_RESULTS_SORT,
                }
    pageinfo.update(paginate.paginate(result_count, current_page))
    return render_to_response('search/search_result.jinja',
                              {"manifestations": manifestations, "page": pageinfo}
                              )