Anonymous avatar Anonymous committed 89f29ce

Bookmarks are now being saved into the database. Bookmarking functionality currently doesn't use javascript. Adding that in next phase.

Comments (0)

Files changed (14)

admin_tools/media/admin_tools/css/dashboard-ie.css

-/* todo: this fucker of ie6 doesn't want the dashboard to take full width... */
+/* todo: ie6 doesn't want the dashboard to take full width... */
 
 html, body {
     _overflow: auto;

admin_tools/media/admin_tools/css/menu-ie.css

 }
 
 #header #navigation-menu li span {
-    /* fuck you ie */
     display: none;
 }
 

admin_tools/media/admin_tools/css/menu.css

 }
 
 #header #bookmark-button {
+    cursor: pointer;
     position: absolute;
     top: auto;
     right: 15px;
     height: 25px;
     width: 24px;
     margin-top: 4px;
+    border: none;
+    text-indent: -40000px;
     background: transparent url(../images/admin-tools.png) no-repeat 0 -425px;
 }
 

admin_tools/media/admin_tools/js/menu.js

 /**
- * Save/remove bookmarks to/from the bookmark menu item and the cookie.
+ * Save/remove bookmarks to/from the bookmark menu item and the database
  *
  * @param string url        The current page url path (request.get_full_path)
  * @param string title      The current page title
  * @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) : [];
+    //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 a span').remove();
                 jQuery('#navigation-menu li.bookmark').addClass('disabled');
             }
-            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;
-                }
-            }
+            //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;
+            //    }
+            //}
         } else {
             title = prompt(prompt_msg, title);
             if (!title) {

admin_tools/menu/forms.py

+from django import forms
+
+from admin_tools.menu.models import Bookmark
+
+
+class BookmarkForm(forms.ModelForm):
+    """
+    This form allows the user to edit bookmarks. It doesn't show the user field.
+    It expects the user to be passed in from the view.
+    """
+
+    def __init__(self, user, *args, **kwargs):
+        super(BookmarkForm, self).__init__(*args, **kwargs)
+        self.user = user
+
+    def save(self, *args, **kwargs):
+        bookmark = super(BookmarkForm, self).save(*args, commit=False, **kwargs)
+        bookmark.user = self.user
+        return bookmark.save()
+
+    class Meta:
+        fields = ('url', 'title')
+        model = Bookmark

admin_tools/menu/models.py

 This module contains the base classes for menu and menu items.
 """
 
+from django.db import models
 from django.contrib import admin
 from django.core.urlresolvers import reverse
 from django.utils.safestring import mark_safe
 from django.utils.text import capfirst
 from django.utils.translation import ugettext_lazy as _
 from admin_tools.utils import AppListElementMixin
-from admin_tools.menu.utils import get_menu_bookmarks
+
+
+class Bookmark(models.Model):
+    """
+    This model represents a user created bookmark.
+    """
+    user = models.ForeignKey('auth.User')
+    url = models.CharField(max_length=255)
+    title = models.CharField(max_length=255)
 
 
 class Menu(object):
         """
         Please refer to the ``MenuItem::init_with_context()`` documentation.
         """
-        for b in get_menu_bookmarks(context['request']):
+        for b in Bookmark.objects.filter(user=context['request'].user):
             self.children.append(MenuItem(
-                url=b['url'],
-                title=mark_safe(b['title'])
+                url=b.url,
+                title=mark_safe(b.title)
             ))
         if not len(self.children):
             self.enabled = False

admin_tools/menu/templates/menu/delete_confirm.html

+{% extends "admin/base_site.html" %}
+
+{% block content %}
+
+<p>Are you sure you want to delete this bookmark?</p>
+
+<p>{{ bookmark.name }} - {{ bookmark.url }}</p>
+
+<form action="." method="POST">
+    <p><input type="submit" value="Delete" /></p>
+</form>
+
+{% endblock %}

admin_tools/menu/templates/menu/form.html

+{% extends "admin/base_site.html" %}
+
+{% block content %}
+
+<form action="." method="POST">
+    {{ form.as_p }}
+    <p><input type="submit" value="Save" /></p>
+</form>
+
+{% endblock %}

admin_tools/menu/templates/menu/menu.html

         document.write(unescape('%3Cscript src="' + script_url + '" type="text/javascript"%3E%3C/script%3E'));
     }
 </script>
-<script type="text/javascript" charset="utf-8">
-    // load jquery cookie if it's not loaded yet
-    if (typeof jQuery.cookie == 'undefined') {
-        var script_url = '{{ media_url }}/admin_tools/js/jquery/jquery.cookie.min.js';
-        document.write(unescape('%3Cscript src="' + script_url + '" type="text/javascript"%3E%3C/script%3E'));
-    }
-</script>
 <script type="text/javascript" charset="utf-8" src="{{ media_url }}/admin_tools/js/menu.js"></script>
 <!--[if IE 6]>
 <script type="text/javascript">
 </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' %}");
+        process_bookmarks("{{ request.get_full_path }}", "{{ title }}", "{% trans 'Please enter a name for the bookmark' %}", "{% url add_bookmark %}", "{% url delete_bookmark bookmark.id %}");
 });
 </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>
+{% 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>
+{% 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/templatetags/admin_tools_menu_tags.py

 from django import template
 from django.conf import settings
 from django.http import HttpRequest
-from admin_tools.menu.models import BookmarkMenuItem
-from admin_tools.menu.utils import get_admin_menu, get_menu_bookmarks
+from admin_tools.menu.models import Bookmark, BookmarkMenuItem
+from admin_tools.menu.utils import get_admin_menu
 
 register = template.Library()
 tag_func = register.inclusion_tag('menu/dummy.html', takes_context=True)
 
     menu.init_with_context(context)
     has_bookmark_item = False
-    page_is_bookmarked = False
     if len([c for c in menu.children if isinstance(c, BookmarkMenuItem)]) > 0:
         has_bookmark_item = True
+        url = context['request'].get_full_path()
         try:
-            request = context['request']
-            page_is_bookmarked = len([b for b in get_menu_bookmarks(request) \
-                if b['url'] == request.get_full_path()]) > 0
-        except Exception, exc:
-            pass
+            bookmark = Bookmark.objects.get(user=context['request'].user, url=url)
+        except Bookmark.DoesNotExist:
+            bookmark = None
 
     context.update({
         'template': menu.template,
         'menu': menu,
         'media_url': settings.MEDIA_URL.rstrip('/'),
         'has_bookmark_item': has_bookmark_item,
-        'page_is_bookmarked': page_is_bookmarked,
+        'bookmark': bookmark,
     })
     return context
 admin_tools_render_menu = tag_func(admin_tools_render_menu)

admin_tools/menu/urls.py

+from django.conf.urls.defaults import *
+
+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'),
+)

admin_tools/menu/utils.py

 from django.conf import settings
 from django.core.exceptions import ImproperlyConfigured
 from django.utils.importlib import import_module
-from django.utils import simplejson
 
 
 def get_admin_menu():
             'cannot be imported: %s' % exc.message
         ))
     return getattr(mod, inst)()
-
-
-def get_menu_bookmarks(request):
-    """
-    Returns the bookmarked items or raise an exception.
-    """
-    json_str = urllib.unquote(request.COOKIES.get('menu.bookmarks', ''))
-    if json_str:
-        return simplejson.loads(json_str)
-    return []

admin_tools/menu/views.py

-# Create your views here.
+from django.contrib.auth.decorators import login_required
+from django.http import HttpResponse, HttpResponseRedirect
+from django.shortcuts import get_object_or_404
+from django.views.generic.simple import direct_to_template
+
+try:
+    from django.views.decorators import csrf_exempt
+except ImportError:
+    from django.contrib.csrf.middleware import csrf_exempt
+
+from forms import BookmarkForm
+from models import Bookmark
+
+
+@login_required
+@csrf_exempt
+def add_bookmark(request):
+    if request.method == "POST":
+        form = BookmarkForm(user=request.user, data=request.POST)
+        if form.is_valid():
+            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')
+    else:
+        form = BookmarkForm(user=request.user)
+    return direct_to_template(request, 'menu/form.html', {
+        'form': form,   
+        'title': 'Add Bookmark',
+    })
+
+
+@login_required
+@csrf_exempt
+def edit_bookmark(request, id):
+    bookmark = get_object_or_404(Bookmark, id=id)
+    if request.method == "POST":
+        form = BookmarkForm(user=request.user, data=request.POST, instance=bookmark)
+        if form.is_valid():
+            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'))
+            return HttpResponse('Saved')
+    else:
+        form = BookmarkForm(user=request.user, instance=bookmark)
+    return direct_to_template(request, 'menu/form.html', {
+        'form': form,   
+        'title': 'Edit Bookmark',
+    })
+
+
+@login_required
+@csrf_exempt
+def remove_bookmark(request, id):
+    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')
+    return direct_to_template(request, 'menu/delete_confirm.html', {
+        'bookmark': bookmark,
+        'title': 'Delete Bookmark',
+    })

admin_tools/urls.py

+from django.conf.urls.defaults import *
+
+urlpatterns = patterns('',
+    url(r'^menu/', include('admin_tools.menu.urls')),
+)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.