Skip to content
Browse files

Update for new coding standards, removed Feed, and changed to django-…

…taggit
  • Loading branch information...
1 parent ba6a439 commit ea40181306f2a67359f5373150d2604fb2e57429 @paltman paltman committed
Showing with 199 additions and 150 deletions.
  1. +4 −1 bookmarks/admin.py
  2. +0 −59 bookmarks/feeds.py
  3. +5 −8 bookmarks/forms.py
  4. +19 −27 bookmarks/models.py
  5. +5 −16 bookmarks/urls.py
  6. +30 −20 bookmarks/views.py
  7. +136 −19 setup.py
View
5 bookmarks/admin.py
@@ -1,8 +1,11 @@
from django.contrib import admin
+
from bookmarks.models import Bookmark, BookmarkInstance
+
class BookmarkAdmin(admin.ModelAdmin):
- list_display = ('url', 'description', 'added', 'adder',)
+ list_display = ["url", "description", "added", "adder"]
+
admin.site.register(Bookmark, BookmarkAdmin)
admin.site.register(BookmarkInstance)
View
59 bookmarks/feeds.py
@@ -1,59 +0,0 @@
-from atomformat import Feed
-from django.core.urlresolvers import reverse
-from django.conf import settings
-from django.contrib.sites.models import Site
-from django.contrib.auth.models import User
-from django.shortcuts import get_object_or_404
-from bookmarks.models import Bookmark
-from django.template.defaultfilters import linebreaks, escape, capfirst
-from datetime import datetime
-
-ITEMS_PER_FEED = getattr(settings, 'PINAX_ITEMS_PER_FEED', 20)
-
-class BookmarkFeed(Feed):
- def item_id(self, bookmark):
- return bookmark.url
-
- def item_title(self, bookmark):
- return bookmark.description
-
- def item_updated(self, bookmark):
- return bookmark.added
-
- def item_published(self, bookmark):
- return bookmark.added
-
- def item_content(self, bookmark):
- return {"type" : "html", }, linebreaks(escape(bookmark.note))
-
- def item_links(self, bookmark):
- return [{"href" : self.item_id(bookmark)}]
-
- def item_authors(self, bookmark):
- return [{"name" : bookmark.adder.username}]
-
- def feed_id(self):
- return 'http://%s/feeds/bookmarks/' % Site.objects.get_current().domain
-
- def feed_title(self):
- return 'Bookmark Feed'
-
- def feed_updated(self):
- qs = Bookmark.objects.all()
- # We return an arbitrary date if there are no results, because there
- # must be a feed_updated field as per the Atom specifications, however
- # there is no real data to go by, and an arbitrary date can be static.
- if qs.count() == 0:
- return datetime(year=2008, month=7, day=1)
- return qs.latest('added').added
-
- def feed_links(self):
- absolute_url = reverse('bookmarks.views.bookmarks')
- complete_url = "http://%s%s" % (
- Site.objects.get_current().domain,
- absolute_url,
- )
- return ({'href': complete_url},)
-
- def items(self):
- return Bookmark.objects.order_by("-added")[:ITEMS_PER_FEED]
View
13 bookmarks/forms.py
@@ -1,27 +1,25 @@
from django import forms
from django.utils.translation import ugettext_lazy as _
-from tagging.forms import TagField
+from bookmarks.models import BookmarkInstance
-from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
- tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
- self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
+ self.fields.keyOrder = ["url", "description", "note", "redirect"]
def clean(self):
- if 'url' not in self.cleaned_data:
+ if "url" not in self.cleaned_data:
return
- if BookmarkInstance.objects.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
+ if BookmarkInstance.objects.filter(bookmark__url=self.cleaned_data["url"], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
@@ -32,9 +30,8 @@ def should_redirect(self):
return False
def save(self, commit=True):
- self.instance.url = self.cleaned_data['url']
+ self.instance.url = self.cleaned_data["url"]
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
- #fields = ('url', 'description', 'note', 'redirect')
View
46 bookmarks/models.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+import datetime
import urlparse
from django.db import models
@@ -6,8 +6,7 @@
from django.contrib.auth.models import User
-from tagging.fields import TagField
-from tagging.models import Tag
+from taggit.managers import TaggableManager
"""
A Bookmark is unique to a URL whereas a BookmarkInstance represents a
@@ -25,54 +24,47 @@
class Bookmark(models.Model):
url = models.URLField(unique=True)
- description = models.CharField(_('description'), max_length=100)
- note = models.TextField(_('note'), blank=True)
+ description = models.CharField(_("description"), max_length=100)
+ note = models.TextField(_("note"), blank=True)
- has_favicon = models.BooleanField(_('has favicon'))
- favicon_checked = models.DateTimeField(_('favicon checked'), default=datetime.now)
+ has_favicon = models.BooleanField(_("has favicon"))
+ favicon_checked = models.DateTimeField(_("favicon checked"), default=datetime.datetime.now)
- adder = models.ForeignKey(User, related_name="added_bookmarks", verbose_name=_('adder'))
- added = models.DateTimeField(_('added'), default=datetime.now)
+ adder = models.ForeignKey(User, related_name="added_bookmarks", verbose_name=_("adder"))
+ added = models.DateTimeField(_("added"), default=datetime.datetime.now)
- # tags = TagField()
def get_favicon_url(self, force=False):
"""
return the URL of the favicon (if it exists) for the site this
bookmark is on other return None.
- If force=True, the URL will be calculated even if it doesn't
+ If force=True, the URL will be calculated even if it does not
exist.
"""
if self.has_favicon or force:
- base_url = '%s://%s' % urlparse.urlsplit(self.url)[:2]
- favicon_url = urlparse.urljoin(base_url, 'favicon.ico')
+ base_url = "%s://%s" % urlparse.urlsplit(self.url)[:2]
+ favicon_url = urlparse.urljoin(base_url, "favicon.ico")
return favicon_url
return None
- def all_tags(self, min_count=False):
- return Tag.objects.usage_for_model(BookmarkInstance, counts=False, min_count=None, filters={'bookmark': self.id})
-
- def all_tags_with_counts(self, min_count=False):
- return Tag.objects.usage_for_model(BookmarkInstance, counts=True, min_count=None, filters={'bookmark': self.id})
-
def __unicode__(self):
return self.url
class Meta:
- ordering = ('-added', )
+ ordering = ["-added", ]
class BookmarkInstance(models.Model):
- bookmark = models.ForeignKey(Bookmark, related_name="saved_instances", verbose_name=_('bookmark'))
- user = models.ForeignKey(User, related_name="saved_bookmarks", verbose_name=_('user'))
- saved = models.DateTimeField(_('saved'), default=datetime.now)
+ bookmark = models.ForeignKey(Bookmark, related_name="saved_instances", verbose_name=_("bookmark"))
+ user = models.ForeignKey(User, related_name="saved_bookmarks", verbose_name=_("user"))
+ saved = models.DateTimeField(_("saved"), default=datetime.datetime.now)
- description = models.CharField(_('description'), max_length=100)
- note = models.TextField(_('note'), blank=True)
+ description = models.CharField(_("description"), max_length=100)
+ note = models.TextField(_("note"), blank=True)
- tags = TagField()
+ tags = TaggableManager()
def save(self, force_insert=False, force_update=False):
try:
@@ -91,4 +83,4 @@ def delete(self):
bookmark.delete()
def __unicode__(self):
- return _("%(bookmark)s for %(user)s") % {'bookmark':self.bookmark, 'user':self.user}
+ return _("%(bookmark)s for %(user)s") % {"bookmark":self.bookmark, "user":self.user}
View
21 bookmarks/urls.py
@@ -1,20 +1,9 @@
from django.conf.urls.defaults import *
-# for voting
-from voting.views import vote_on_object
-from bookmarks.models import Bookmark
-urlpatterns = patterns('',
- url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"),
- url(r'^your_bookmarks/$', 'bookmarks.views.your_bookmarks', name="your_bookmarks"),
- url(r'^add/$', 'bookmarks.views.add', name="add_bookmark"),
- url(r'^(\d+)/delete/$', 'bookmarks.views.delete', name="delete_bookmark_instance"),
-
- # for voting
- (r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
- vote_on_object, dict(
- model=Bookmark,
- template_object_name='bookmark',
- template_name='kb/link_confirm_vote.html',
- allow_xmlhttprequest=True)),
+urlpatterns = patterns("",
+ url(r"^$", "bookmarks.views.bookmarks", name="all_bookmarks"),
+ url(r"^your_bookmarks/$", "bookmarks.views.your_bookmarks", name="your_bookmarks"),
+ url(r"^add/$", "bookmarks.views.add", name="add_bookmark"),
+ url(r"^(\d+)/delete/$", "bookmarks.views.delete", name="delete_bookmark_instance"),
)
View
50 bookmarks/views.py
@@ -1,23 +1,25 @@
-from datetime import datetime
-import urlparse
+import datetime
import urllib2
+from django.core.urlresolvers import reverse
+from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
+from django.utils.translation import ugettext_lazy as _
+
from django.contrib.auth.decorators import login_required
-from django.http import HttpResponseRedirect
-from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
-from django.utils.translation import ugettext_lazy as _
-
-from bookmarks.models import Bookmark, BookmarkInstance
from bookmarks.forms import BookmarkInstanceForm
+from bookmarks.models import Bookmark, BookmarkInstance
+
def bookmarks(request):
bookmarks = Bookmark.objects.all().order_by("-added")
if request.user.is_authenticated():
- user_bookmarks = Bookmark.objects.filter(saved_instances__user=request.user)
+ user_bookmarks = Bookmark.objects.filter(
+ saved_instances__user=request.user
+ )
else:
user_bookmarks = []
return render_to_response("bookmarks/bookmarks.html", {
@@ -28,14 +30,16 @@ def bookmarks(request):
@login_required
def your_bookmarks(request):
- bookmark_instances = BookmarkInstance.objects.filter(user=request.user).order_by("-saved")
+ bookmark_instances = BookmarkInstance.objects.filter(
+ user=request.user
+ ).order_by("-saved")
return render_to_response("bookmarks/your_bookmarks.html", {
"bookmark_instances": bookmark_instances,
}, context_instance=RequestContext(request))
+
@login_required
def add(request):
-
if request.method == "POST":
bookmark_form = BookmarkInstanceForm(request.user, request.POST)
if bookmark_form.is_valid():
@@ -53,20 +57,24 @@ def add(request):
##"User-Agent": settings.URL_VALIDATOR_USER_AGENT
}
req = urllib2.Request(bookmark.get_favicon_url(force=True), None, headers)
- u = urllib2.urlopen(req)
+ urllib2.urlopen(req)
has_favicon = True
except:
has_favicon = False
bookmark.has_favicon = has_favicon
- bookmark.favicon_checked = datetime.now()
+ bookmark.favicon_checked = datetime.datetime.now()
bookmark.save()
if bookmark_form.should_redirect():
return HttpResponseRedirect(bookmark.url)
else:
- request.user.message_set.create(message=_("You have saved bookmark '%(description)s'") % {'description': bookmark_instance.description})
- return HttpResponseRedirect(reverse("bookmarks.views.bookmarks"))
+ request.user.message_set.create(
+ message=_("You have saved bookmark '%(description)s'") % {
+ "description": bookmark_instance.description
+ }
+ )
+ return HttpResponseRedirect(reverse("all_bookmarks"))
else:
initial = {}
if "url" in request.GET:
@@ -81,7 +89,7 @@ def add(request):
else:
bookmark_form = BookmarkInstanceForm()
- bookmarks_add_url = "http://" + Site.objects.get_current().domain + reverse(add)
+ bookmarks_add_url = "http://" + Site.objects.get_current().domain + reverse("add_bookmark")
bookmarklet = "javascript:location.href='%s?url='+encodeURIComponent(location.href)+';description='+encodeURIComponent(document.title)+';redirect=on'" % bookmarks_add_url
return render_to_response("bookmarks/add.html", {
@@ -89,18 +97,20 @@ def add(request):
"bookmark_form": bookmark_form,
}, context_instance=RequestContext(request))
+
@login_required
def delete(request, bookmark_instance_id):
-
- bookmark_instance = get_object_or_404(BookmarkInstance, id=bookmark_instance_id)
+ bookmark_instance = get_object_or_404(
+ BookmarkInstance,
+ pk=bookmark_instance_id
+ )
if request.user == bookmark_instance.user:
bookmark_instance.delete()
request.user.message_set.create(message="Bookmark Deleted")
-
+
if "next" in request.GET:
next = request.GET["next"]
else:
- next = reverse("bookmarks.views.bookmarks")
+ next = reverse("all_bookmarks")
return HttpResponseRedirect(next)
-
View
155 setup.py
@@ -1,23 +1,140 @@
-from distutils.core import setup
+import codecs
+import os
+import sys
+
+from distutils.util import convert_path
+from fnmatch import fnmatchcase
+from setuptools import setup, find_packages
+
+
+def read(fname):
+ return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
+
+
+# Provided as an attribute, so you can append to these instead
+# of replicating them:
+standard_exclude = ["*.py", "*.pyc", "*$py.class", "*~", ".*", "*.bak"]
+standard_exclude_directories = [
+ ".*", "CVS", "_darcs", "./build", "./dist", "EGG-INFO", "*.egg-info"
+]
+
+
+# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
+# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
+# Note: you may want to copy this into your setup.py file verbatim, as
+# you can't import this from another package, when you don't know if
+# that package is installed yet.
+def find_package_data(
+ where=".",
+ package="",
+ exclude=standard_exclude,
+ exclude_directories=standard_exclude_directories,
+ only_in_packages=True,
+ show_ignored=False):
+ """
+ Return a dictionary suitable for use in ``package_data``
+ in a distutils ``setup.py`` file.
+
+ The dictionary looks like::
+
+ {"package": [files]}
+
+ Where ``files`` is a list of all the files in that package that
+ don"t match anything in ``exclude``.
+
+ If ``only_in_packages`` is true, then top-level directories that
+ are not packages won"t be included (but directories under packages
+ will).
+
+ Directories matching any pattern in ``exclude_directories`` will
+ be ignored; by default directories with leading ``.``, ``CVS``,
+ and ``_darcs`` will be ignored.
+
+ If ``show_ignored`` is true, then all the files that aren"t
+ included in package data are shown on stderr (for debugging
+ purposes).
+
+ Note patterns use wildcards, or can be exact paths (including
+ leading ``./``), and all searching is case-insensitive.
+ """
+ out = {}
+ stack = [(convert_path(where), "", package, only_in_packages)]
+ while stack:
+ where, prefix, package, only_in_packages = stack.pop(0)
+ for name in os.listdir(where):
+ fn = os.path.join(where, name)
+ if os.path.isdir(fn):
+ bad_name = False
+ for pattern in exclude_directories:
+ if (fnmatchcase(name, pattern)
+ or fn.lower() == pattern.lower()):
+ bad_name = True
+ if show_ignored:
+ print >> sys.stderr, (
+ "Directory %s ignored by pattern %s"
+ % (fn, pattern))
+ break
+ if bad_name:
+ continue
+ if (os.path.isfile(os.path.join(fn, "__init__.py"))
+ and not prefix):
+ if not package:
+ new_package = name
+ else:
+ new_package = package + "." + name
+ stack.append((fn, "", new_package, False))
+ else:
+ stack.append((fn, prefix + name + "/", package, only_in_packages))
+ elif package or not only_in_packages:
+ # is a file
+ bad_name = False
+ for pattern in exclude:
+ if (fnmatchcase(name, pattern)
+ or fn.lower() == pattern.lower()):
+ bad_name = True
+ if show_ignored:
+ print >> sys.stderr, (
+ "File %s ignored by pattern %s"
+ % (fn, pattern))
+ break
+ if bad_name:
+ continue
+ out.setdefault(package, []).append(prefix+name)
+ return out
+
+
+PACKAGE = "bookmarks"
+NAME = "django-bookmarks"
+DESCRIPTION = "A reusable app for bookmark management"
+AUTHOR = "Eldarion"
+AUTHOR_EMAIL = "developers@eldarion.com"
+URL = "http://github.com/pinax/django-bookmarks"
+VERSION = __import__(PACKAGE).__version__
+
setup(
- name='django-bookmarks',
- version=__import__('bookmarks').__version__,
- description='A reusable Django app for bookmark management.',
- author='James Tauber',
- author_email='jtauber@jtauber.com',
- url='http://code.google.com/p/django-bookmarks/',
- packages=[
- 'bookmarks',
- ],
- package_dir={'bookmarks': 'bookmarks'},
+ name=NAME,
+ version=VERSION,
+ description=DESCRIPTION,
+ long_description=read("README"),
+ author=AUTHOR,
+ author_email=AUTHOR_EMAIL,
+ license="MIT",
+ url=URL,
+ packages=find_packages(exclude=["tests.*", "tests"]),
+ package_data=find_package_data(PACKAGE, only_in_packages=False),
classifiers=[
- 'Development Status :: 3 - Alpha',
- 'Environment :: Web Environment',
- 'Intended Audience :: Developers',
- 'License :: OSI Approved :: MIT License',
- 'Operating System :: OS Independent',
- 'Programming Language :: Python',
- 'Framework :: Django',
- ]
+ "Development Status :: 3 - Alpha",
+ "Environment :: Web Environment",
+ "Intended Audience :: Developers",
+ "License :: OSI Approved :: MIT License",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python",
+ "Framework :: Django",
+ ],
+ setup_requires=[
+ "django-taggit==0.9.3"
+ ],
+ zip_safe=False
)
+

0 comments on commit ea40181

Please sign in to comment.
Something went wrong with that request. Please try again.