lunes, 9 de diciembre de 2013

django - Add a haysack Full Text Search in a model window

Well, I have been creating a website and found a way to "popou" a modal window that would contain an FTS.

The credits of this procedure are not mine, these belong to
Mike Hibbert: http://www.youtube.com/user/MickeySoFine1972
Kevin Lew: http://www.queness.com/post/77/simple-jquery-modal-window-tutorial

You can follow mikes tutorial to setup an FTS. I will do somethig similar adding the Lew's modal window.


I will start by creating the model window.

1. Add the code in a template where you cant to add the link that will call the model window:

<a href="#dialog_presenter" name="modal">Add presenter jquery</a>

#dialog presenter is the div name of the model window.

2. Add the corresponding div, might be at the top of your html.

    <!-- #dialog is the id of a DIV defined in the code below -->
    <div id="boxes">

        <!-- #customize your modal window here -->
        <div id="dialog_presenter" class="window">
            <b>Select presenter to add </b>


            <!-- close button is defined as close class -->
            <a href="#" class="close">Close it</a>
        </div>

        <!-- Do not remove div#mask, because you'll need it to fill the whole screen -->
        <div id="mask"></div>
    </div>

Notice that so far had jkust been added "select presenter to Add" ... Nothing else in the model window.

3.  Add some style:


    <style>
    /* Z-index of #mask must lower than #boxes .window */
    #mask {
    position:absolute;
    z-index:9000;
    background-color:#cccccc;
    display:none;
    }
    #boxes  .window {
    position:fixed;
    width:440px;
    height:200px;
    display:none;
    z-index:9999;
    padding:20px;
    }

    /* Customize your modal window here, you can add background image too */
    #boxes #dialog_presenter  {
    width:375px;
    height:203px;
    }
    </style>

4. Add the javascript for a modal window:


    <script>
    $(document).ready(function() {   
        //select all the a tag with name equal to modal
        $('a[name=modal]').click(function(e) {
            //Cancel the link behavior
            e.preventDefault();
            //Get the A tag
            var id = $(this).attr('href');
       
            //Get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();
       
            //Set height and width to mask to fill up the whole screen
            $('#mask').css({'width':maskWidth,'height':maskHeight});
           
            //transition effect       
            $('#mask').fadeIn(1000);   
            $('#mask').fadeTo("slow",0.8);   
       
            //Get the window height and width
            var winH = $(window).height();
            var winW = $(window).width();
            //Set the popup window to center
            $(id).css('top', winH/2-$(id).height()/2);
            $(id).css('left', winW/2-$(id).width()/2);
       
            //transition effect
            $(id).fadeIn(2000);
       
        });
       
        //if close button is clicked
        $('.window .close').click(function (e) {
            //Cancel the link behavior
            e.preventDefault();
            $('#mask, .window').hide();
        });       
       
        //if mask is clicked
        $('#mask').click(function () {
            $(this).hide();
            $('.window').hide();
        });           
       
    });
    </script>


THAT IS IT FOR THE MODAL WINDOW


5. Now for FTS install whoosh and haysack:

pip install whoosh
pip install django-haystack




6. Add to your project settings.py:

WHOOSH_INDEX = os.path.join(PROJECT_DIRECTORY,'whoosh/')

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': WHOOSH_INDEX,
    },
}


Also... add also to INSTALLED_APPS haytack and django

INSTALLED_APPS = (
    'whoosh',
    'haystack',
)



7. Now I would recommend to follow Mikes youtube's tutorial for FTS, it is clear and complete, just keep in mind that your modal window div would be like:



    <!-- #dialog is the id of a DIV defined in the code below -->
    <div id="boxes">
        <!-- #customize your modal window here -->
        <div id="dialog_presenter" class="window">
            <b>Select presenter to add </b>
            <h3> search </h3>
            {% csrf_token%}
            <input type="text" id="search_presenter" name="search_presenter" />
            <ul id="search-results-presenter">
            </ul>

            <!-- close button is defined as close class -->
            <a href="#" class="close">Close it</a>
        </div>
        <!-- Do not remove div#mask, because you'll need it to fill the whole screen -->
        <div id="mask"></div>
    </div>




Notice that the search input is what the FTS uses as source textbox.



I will just remark the most important steps:

8.- As already said in 7, add the search input.

9.- on ajax.js (java script) add:

$(function(){

    $('#search_presenter').keyup(function() {

        $.ajax({
            type: "POST",
            url: "/ticwiapp/search_user_add_presenter_ajax/",
            data: {
                'search_text' : $('#search_presenter').val(),
                'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccessPresenter,
            dataType: 'html'
        });

    });

});


function searchSuccessPresenter(data, textStatus, jqXHR)
{
    $('#search-results-presenter').html(data);
}


Where search-results-presenter are the results shown in the <ul> of step 7.

10. on urls file addthe udr and view that will attend the javascript of step 9.

url(r'^search_user_add_presenter_ajax/$', 'myapp.views.search_user_add_presenter_ajax'),

11. on myapp views add myapp.views.search_user_add_presenter_ajax like:

def search_user_add_presenter_ajax(request):

    args = {}
    args.update(csrf(request))
    args['user'] = request.user
   
    # Follow create a haystack object instead a queryset
    args['all_users']  = SearchQuerySet().autocomplete(content_auto=request.POST.get('search_text',''))


    return render_to_response('search_user_add_presenter_ajax.html',args)

12. Create search_user_add_presenter_ajax.html template, this is specified in the return of step 11.

Follow is an example:

{% load static %}


{% if all_users.count > 0 %}
{% for one_user in all_users %}
<br>  {{ one_user.object.first_name }} {{ one_user.object.last_name }}
<a href = "/ticwiapp/add_presenter_now/{{ event.id }}/{{ one_user.object.id }}/registered">Add presenter </a>
{% endfor %}

{% else %}

<p>No users in database!</p>

{% endif %}



There you are!! Enjoy!

 P.D. Looks like Egyptians had invented flags




No hay comentarios:

Publicar un comentario en la entrada