Commits

Anonymous committed 73251a3

Now using javascript to do bookmarks. Views got a little more complicated to handle the ajax case.

  • Participants
  • Parent commits 89f29ce

Comments (0)

Files changed (9)

admin_tools/media/admin_tools/css/menu.css

     width: 24px;
     margin-top: 4px;
     border: none;
-    text-indent: -40000px;
+    text-indent: -5000px;
+    overflow: hidden;
     background: transparent url(../images/admin-tools.png) no-repeat 0 -425px;
 }
 

admin_tools/media/admin_tools/js/menu.js

  * @return void
  */
 var process_bookmarks = function(url, title, prompt_msg) {
-    //var json_str = jQuery.cookie('menu.bookmarks');
-    //var bookmarks = json_str ? JSON.parse(json_str) : [];
-    jQuery('#bookmark-button').click(function() {
-        if (jQuery(this).hasClass('bookmarked')) {
-            jQuery(this).removeClass('bookmarked');
-            jQuery('#navigation-menu li.bookmark ul li a[href="' + url + '"]').parent().remove();
-            if (!jQuery('#navigation-menu li.bookmark ul li').length) {
-                jQuery('#navigation-menu li.bookmark ul').remove();
-                jQuery('#navigation-menu li.bookmark a span').remove();
-                jQuery('#navigation-menu li.bookmark').addClass('disabled');
+    var $ = jQuery;
+    $('#bookmark-button').live('click', function(e) {
+        var submit_url = $("#bookmark-form").attr('action');
+        e.preventDefault();
+        if ($(this).hasClass('bookmarked')) {
+            $(this).removeClass('bookmarked');
+            $('#navigation-menu li.bookmark ul li a[href="' + url + '"]').parent().remove();
+            if (!$('#navigation-menu li.bookmark ul li').length) {
+                $('#navigation-menu li.bookmark ul').remove();
+                $('#navigation-menu li.bookmark a span').remove();
+                $('#navigation-menu li.bookmark').addClass('disabled');
             }
-            //Save bookmark
-            //
-            //for (var i=0; i < bookmarks.length; i++) {
-            //    if (bookmarks[i].url == url) {
-            //        bookmarks.splice(i, 1);
-            //        jQuery.cookie('menu.bookmarks', JSON.stringify(bookmarks), {
-            //            expires: 1825,
-            //            path: '/admin/' // harcode path to have a unique cookie across pages
-            //        });
-            //        break;
-            //    }
-            //}
+            //Drop bookmark and switch form
+            $.post(submit_url, $("#bookmark-form").serialize(), function(data) {
+                $("#bookmark-form").replaceWith(data.replace('**title**', title));
+            }, 'html');
         } else {
             title = prompt(prompt_msg, title);
             if (!title) {
                 return;
             }
-            jQuery(this).addClass('bookmarked');
-            if (!jQuery('#navigation-menu li.bookmark ul').length) {
-                jQuery('#navigation-menu li.bookmark a').prepend('<span class="icon"/>');
-                jQuery('#navigation-menu li.bookmark').append('<ul/>');
+            $(this).addClass('bookmarked');
+            if (!$('#navigation-menu li.bookmark ul').length) {
+                $('#navigation-menu li.bookmark a').prepend('<span class="icon"/>');
+                $('#navigation-menu li.bookmark').append('<ul/>');
+                $('#navigation-menu li.bookmark').removeClass('disabled');
             }
-            jQuery('#navigation-menu li.bookmark ul').append(
+            $('#navigation-menu li.bookmark ul').append(
                 '<li><a href="' + url + '">' + title + '</a></li>'
             );
-            jQuery('#navigation-menu li.bookmark').removeClass('disabled');
-            var already_bookmarked = false;
-            for (var i=0; i < bookmarks.length; i++) {
-                if (bookmarks[i].url == url) {
-                    already_bookmarked = true;
-                }
-            }
-            if (!already_bookmarked) {
-                bookmarks.push({url: url, title: title});
-                jQuery.cookie('menu.bookmarks', JSON.stringify(bookmarks), {
-                    expires: 1825,
-                    path: '/admin/' // harcode path to have a unique cookie across pages
-                });
-            }
+            // Save bookmark and switch form
+            $.post(submit_url, $("#bookmark-form").serialize(), function(data) {
+                $("#bookmark-form").replaceWith(data);
+            }, 'html');
         }
     });
 };

admin_tools/menu/forms.py

     def save(self, *args, **kwargs):
         bookmark = super(BookmarkForm, self).save(*args, commit=False, **kwargs)
         bookmark.user = self.user
-        return bookmark.save()
+        bookmark.save()
+        return bookmark
 
     class Meta:
         fields = ('url', 'title')

admin_tools/menu/templates/menu/add_bookmark_form.html

+<form id="bookmark-form" action="{% url add-bookmark %}" method="POST">
+    <input type="hidden" name="next" value="{% firstof url request.get_full_path|urlencode %}" />
+    <input type="hidden" name="url" value="{% firstof url request.get_full_path|urlencode %}" />
+    <input type="hidden" name="title" value="{{ title }}" />
+    <button id="bookmark-button" type="submit">Add</button>
+</form>

admin_tools/menu/templates/menu/menu.html

 </script>
 <![endif]-->
 {% if has_bookmark_item %}
-{% comment %}
 <script type="text/javascript">
 jQuery(function($) {
-        process_bookmarks("{{ request.get_full_path }}", "{{ title }}", "{% trans 'Please enter a name for the bookmark' %}", "{% url add_bookmark %}", "{% url delete_bookmark bookmark.id %}");
+        process_bookmarks("{{ request.get_full_path }}", "{{ title }}", "{% trans 'Please enter a name for the bookmark' %}");
 });
 </script>
-{% endcomment %}
 
 {% if bookmark %}
-<form action="{% url remove-bookmark bookmark.id %}" method="POST">
-    <input type="hidden" name="next" value="{{ request.get_full_path|urlencode }}" />
-    <button id="bookmark-button" class="bookmarked" type="submit">Remove</button>
-</form>
+{% include "menu/remove_bookmark_form.html" %}
 {% else %}
-<form action="{% url add-bookmark %}" method="POST">
-    <input type="hidden" name="next" value="{{ request.get_full_path|urlencode }}" />
-    <input type="hidden" name="url" value="{{ request.get_full_path|urlencode }}" />
-    <input type="hidden" name="title" value="{{ title }}" />
-    <button id="bookmark-button" type="submit">Add</button>
-</form>
+{% include "menu/add_bookmark_form.html" %}
 {% endif %}
 
-{% comment %}
-This is the old button
-<a id="bookmark-button" href="#" title="{% trans "Bookmark this page" %}"{% if page_is_bookmarked %} class="bookmarked"{% endif %}></a>
-{% endcomment %}
-
 {% endif %}
 <ul id="navigation-menu">
     {% for item in menu.children %}{% admin_tools_render_menu_item item forloop.counter %}{% endfor %}

admin_tools/menu/templates/menu/remove_bookmark_form.html

+<form id="bookmark-form" action="{% url remove-bookmark bookmark.id %}" method="POST">
+    <input type="hidden" name="next" value="{% firstof url request.get_full_path|urlencode %}" />
+    <button id="bookmark-button" class="bookmarked" type="submit">Remove</button>
+</form>

admin_tools/menu/templatetags/admin_tools_menu_tags.py

         has_bookmark_item = True
         url = context['request'].get_full_path()
         try:
-            bookmark = Bookmark.objects.get(user=context['request'].user, url=url)
-        except Bookmark.DoesNotExist:
+            bookmark = Bookmark.objects.filter(user=context['request'].user, url=url)[0]
+        except IndexError:
             bookmark = None
 
     context.update({

admin_tools/menu/urls.py

 
 urlpatterns = patterns('admin_tools.menu.views',
     url(r'^add_bookmark/$', 'add_bookmark', name='add-bookmark'),
-    url(r'^edit_bookmark/(?P<id>.*)/$', 'edit_bookmark', name='edit-bookmark'),
-    url(r'^remove_bookmark/(?P<id>.*)/$', 'remove_bookmark', name='remove-bookmark'),
+    url(r'^edit_bookmark/(?P<id>.+)/$', 'edit_bookmark', name='edit-bookmark'),
+    url(r'^remove_bookmark/(?P<id>.+)/$', 'remove_bookmark', name='remove-bookmark'),
 )

admin_tools/menu/views.py

 from django.contrib.auth.decorators import login_required
 from django.http import HttpResponse, HttpResponseRedirect
 from django.shortcuts import get_object_or_404
+from django.utils import simplejson
 from django.views.generic.simple import direct_to_template
 
 try:
 @login_required
 @csrf_exempt
 def add_bookmark(request):
+    """
+    This view serves and validates a bookmark form.
+    If requested via ajax it also returns the drop bookmark form to replace the 
+    add bookmark form.
+    """
     if request.method == "POST":
         form = BookmarkForm(user=request.user, data=request.POST)
         if form.is_valid():
-            form.save()
+            bookmark = form.save()
             if not request.is_ajax():
                 request.user.message_set.create(message='Bookmark added')
-            if request.POST.get('next'):
-                return HttpResponseRedirect(request.POST.get('next'))
-            return HttpResponse('Added')
+                if request.POST.get('next'):
+                    return HttpResponseRedirect(request.POST.get('next'))
+                return HttpResponse('Added')
+            return direct_to_template(request, 'menu/remove_bookmark_form.html', {
+                'bookmark': bookmark,
+                'url': bookmark.url,
+            });
     else:
         form = BookmarkForm(user=request.user)
     return direct_to_template(request, 'menu/form.html', {
             form.save()
             if not request.is_ajax():
                 request.user.message_set.create(message='Bookmark updated')
-            if request.POST.get('next'):
-                return HttpResponseRedirect(request.POST.get('next'))
+                if request.POST.get('next'):
+                    return HttpResponseRedirect(request.POST.get('next'))
             return HttpResponse('Saved')
     else:
         form = BookmarkForm(user=request.user, instance=bookmark)
 @login_required
 @csrf_exempt
 def remove_bookmark(request, id):
+    """
+    This view deletes a bookmark.
+    If requested via ajax it also returns the add bookmark form to replace the 
+    drop bookmark form.
+    """
     bookmark = get_object_or_404(Bookmark, id=id)
     if request.method == "POST":
         bookmark.delete()
         if not request.is_ajax():
             request.user.message_set.create(message='Bookmark removed')
-        if request.POST.get('next'):
-            return HttpResponseRedirect(request.POST.get('next'))
-        return HttpResponse('Deleted')
+            if request.POST.get('next'):
+                return HttpResponseRedirect(request.POST.get('next'))
+            return HttpResponse('Deleted')
+        return direct_to_template(request, 'menu/add_bookmark_form.html', {
+            'url': request.POST.get('next'),
+            'title': '**title**' #This gets replaced on the javascript side
+        });
     return direct_to_template(request, 'menu/delete_confirm.html', {
         'bookmark': bookmark,
         'title': 'Delete Bookmark',