1 # -*- coding: utf-8 -*-
2 from django.template import RequestContext
3 from django.shortcuts import render_to_response, get_object_or_404
4 from django.http import HttpResponse, HttpResponseRedirect, Http404
5 from django.core.urlresolvers import reverse
6 from django.db.models import Q
7 from django.contrib.auth.decorators import login_required
8 from django.utils.datastructures import SortedDict
9 from django.views.decorators.http import require_POST
10 from django.contrib import auth
11 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
12 from django.utils import simplejson
13 from django.utils.functional import Promise
14 from django.utils.encoding import force_unicode
15 from django.views.decorators import cache
17 from catalogue import models
18 from catalogue import forms
19 from catalogue.utils import split_tags
20 from newtagging import views as newtagging_views
23 class LazyEncoder(simplejson.JSONEncoder):
24 def default(self, obj):
25 if isinstance(obj, Promise):
26 return force_unicode(obj)
30 @cache.cache_control(must_revalidate=True, max_age=3600)
31 def main_page(request):
32 if request.user.is_authenticated():
33 shelves = models.Tag.objects.filter(category='set', user=request.user)
34 new_set_form = forms.NewSetForm()
35 extra_where = 'NOT catalogue_tag.category = "set"'
36 tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
37 fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
38 extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
39 categories = split_tags(tags)
41 form = forms.SearchForm()
42 return render_to_response('catalogue/main_page.html', locals(),
43 context_instance=RequestContext(request))
46 def book_list(request):
47 books = models.Book.objects.all()
48 form = forms.SearchForm()
50 books_by_first_letter = SortedDict()
52 books_by_first_letter.setdefault(book.title[0], []).append(book)
54 return render_to_response('catalogue/book_list.html', locals(),
55 context_instance=RequestContext(request))
58 @cache.cache_control(must_revalidate=True, max_age=3600)
59 def tagged_object_list(request, tags=''):
60 # Prevent DoS attacks on our database
61 if len(tags.split('/')) > 6:
65 tags = models.Tag.get_tag_list(tags)
66 except models.Tag.DoesNotExist:
70 shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
71 theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
73 model = models.Fragment
75 extra_where = 'NOT catalogue_tag.category = "set"'
76 related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
77 categories = split_tags(related_tags)
80 model=models.Book.objects.filter(parent=None)
82 return newtagging_views.tagged_object_list(
85 queryset_or_model=model,
87 template_name='catalogue/tagged_object_list.html',
88 extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set },
92 def book_detail(request, slug):
93 book = get_object_or_404(models.Book, slug=slug)
94 tags = list(book.tags.filter(~Q(category='set')))
95 categories = split_tags(tags)
96 book_children = book.children.all().order_by('parent_number')
98 form = forms.SearchForm()
99 return render_to_response('catalogue/book_detail.html', locals(),
100 context_instance=RequestContext(request))
103 def book_text(request, slug):
104 book = get_object_or_404(models.Book, slug=slug)
106 for fragment in book.fragments.all():
107 for theme in fragment.tags.filter(category='theme'):
108 book_themes.setdefault(theme, []).append(fragment)
110 book_themes = book_themes.items()
111 book_themes.sort(key=lambda s: s[0].sort_key)
112 return render_to_response('catalogue/book_text.html', locals(),
113 context_instance=RequestContext(request))
120 query = request.GET.get('q', '')
121 tags = request.GET.get('tags', '')
126 tag_list = models.Tag.get_tag_list(tags)
127 tag = models.Tag.objects.get(name=query)
128 except models.Tag.DoesNotExist:
130 book = models.Book.objects.get(title=query)
131 return HttpResponseRedirect(book.get_absolute_url())
132 except models.Book.DoesNotExist:
133 return HttpResponseRedirect(reverse('catalogue.views.main_page'))
136 return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list',
137 kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
141 def tags_starting_with(request):
143 prefix = request.GET['q']
147 books = models.Book.objects.filter(title__icontains=prefix)
148 tags = models.Tag.objects.filter(name__icontains=prefix)
149 if request.user.is_authenticated():
150 tags = tags.filter(~Q(category='set') | Q(user=request.user))
152 tags = tags.filter(~Q(category='set'))
154 completions = [book.title for book in books] + [tag.name for tag in tags]
156 return HttpResponse('\n'.join(completions))
159 return HttpResponse('')
162 # ====================
163 # = Shelf management =
164 # ====================
166 @cache.cache_control(must_revalidate=True, max_age=3600, private=True)
167 def user_shelves(request):
168 shelves = models.Tag.objects.filter(category='set', user=request.user)
169 new_set_form = forms.NewSetForm()
170 return render_to_response('catalogue/user_shelves.html', locals(),
171 context_instance=RequestContext(request))
174 @cache.cache_control(must_revalidate=True, max_age=3600, private=True)
175 def book_sets(request, slug):
176 book = get_object_or_404(models.Book, slug=slug)
177 user_sets = models.Tag.objects.filter(category='set', user=request.user)
178 book_sets = book.tags.filter(category='set', user=request.user)
180 if not request.user.is_authenticated():
181 return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
183 if request.method == 'POST':
184 form = forms.ObjectSetsForm(book, request.user, request.POST)
186 book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
187 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
188 if request.is_ajax():
189 return HttpResponse('<p>Półki zostały zapisane.</p>')
191 return HttpResponseRedirect('/')
193 form = forms.ObjectSetsForm(book, request.user)
194 new_set_form = forms.NewSetForm()
196 return render_to_response('catalogue/book_sets.html', locals(),
197 context_instance=RequestContext(request))
203 def new_set(request):
204 new_set_form = forms.NewSetForm(request.POST)
205 if new_set_form.is_valid():
206 new_set = new_set_form.save(request.user)
208 if request.is_ajax():
209 return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
211 return HttpResponseRedirect('/')
213 return render_to_response('catalogue/book_sets.html', locals(),
214 context_instance=RequestContext(request))
220 def delete_shelf(request, slug):
221 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
224 if request.is_ajax():
225 return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
227 return HttpResponseRedirect('/')
236 form = AuthenticationForm(data=request.POST, prefix='login')
238 auth.login(request, form.get_user())
239 response_data = {'success': True, 'errors': {}}
241 response_data = {'success': False, 'errors': form.errors}
242 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
247 def register(request):
248 registration_form = UserCreationForm(request.POST, prefix='registration')
249 if registration_form.is_valid():
250 user = registration_form.save()
251 user = auth.authenticate(
252 username=registration_form.cleaned_data['username'],
253 password=registration_form.cleaned_data['password1']
255 auth.login(request, user)
256 response_data = {'success': True, 'errors': {}}
258 response_data = {'success': False, 'errors': registration_form.errors}
259 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
263 def logout_then_redirect(request):
265 return HttpResponseRedirect(request.GET.get('next', '/'))