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.cache import cache_page
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)
31 query = request.GET.get('q', '')
32 tags = request.GET.get('tags', '')
37 tag_list = models.Tag.get_tag_list(tags)
38 tag = models.Tag.objects.get(name=query)
39 except models.Tag.DoesNotExist:
41 book = models.Book.objects.get(title=query)
42 return HttpResponseRedirect(book.get_absolute_url())
43 except models.Book.DoesNotExist:
44 return HttpResponseRedirect(reverse('catalogue.views.main_page'))
47 return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list',
48 kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
52 def tags_starting_with(request):
54 prefix = request.GET['q']
58 books = models.Book.objects.filter(title__icontains=prefix)
59 tags = models.Tag.objects.filter(name__icontains=prefix)
60 if request.user.is_authenticated():
61 tags = tags.filter(~Q(category='set') | Q(user=request.user))
63 tags = tags.filter(~Q(category='set'))
65 completions = [book.title for book in books] + [tag.name for tag in tags]
67 return HttpResponse('\n'.join(completions))
70 return HttpResponse('')
73 def main_page(request):
74 if request.user.is_authenticated():
75 shelves = models.Tag.objects.filter(category='set', user=request.user)
76 new_set_form = forms.NewSetForm()
77 extra_where = 'NOT catalogue_tag.category = "set"'
78 tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
79 fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
80 extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
81 categories = split_tags(tags)
83 form = forms.SearchForm()
84 return render_to_response('catalogue/main_page.html', locals(),
85 context_instance=RequestContext(request))
88 def book_list(request):
89 books = models.Book.objects.all()
90 form = forms.SearchForm()
92 books_by_first_letter = SortedDict()
94 books_by_first_letter.setdefault(book.title[0], []).append(book)
96 return render_to_response('catalogue/book_list.html', locals(),
97 context_instance=RequestContext(request))
100 def tagged_object_list(request, tags=''):
101 # Prevent DoS attacks on our database
102 if len(tags.split('/')) > 6:
106 tags = models.Tag.get_tag_list(tags)
107 except models.Tag.DoesNotExist:
111 shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
112 theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
114 model = models.Fragment
116 extra_where = 'NOT catalogue_tag.category = "set"'
117 related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
118 categories = split_tags(related_tags)
121 model=models.Book.objects.filter(parent=None)
123 return newtagging_views.tagged_object_list(
125 tag_model=models.Tag,
126 queryset_or_model=model,
128 template_name='catalogue/tagged_object_list.html',
129 extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set },
133 def book_detail(request, slug):
134 book = get_object_or_404(models.Book, slug=slug)
135 tags = list(book.tags.filter(~Q(category='set')))
136 categories = split_tags(tags)
137 book_children = book.children.all().order_by('parent_number')
139 form = forms.SearchForm()
140 return render_to_response('catalogue/book_detail.html', locals(),
141 context_instance=RequestContext(request))
145 def book_text(request, slug):
146 book = get_object_or_404(models.Book, slug=slug)
148 for fragment in book.fragments.all():
149 for theme in fragment.tags.filter(category='theme'):
150 book_themes.setdefault(theme, []).append(fragment)
152 book_themes = book_themes.items()
153 book_themes.sort(key=lambda s: s[0].sort_key)
154 return render_to_response('catalogue/book_text.html', locals(),
155 context_instance=RequestContext(request))
158 def logout_then_redirect(request):
160 return HttpResponseRedirect(request.GET.get('next', '/'))
164 def register(request):
165 registration_form = UserCreationForm(request.POST, prefix='registration')
166 if registration_form.is_valid():
167 user = registration_form.save()
168 user = auth.authenticate(
169 username=registration_form.cleaned_data['username'],
170 password=registration_form.cleaned_data['password1']
172 auth.login(request, user)
173 response_data = {'success': True, 'errors': {}}
175 response_data = {'success': False, 'errors': registration_form.errors}
176 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
181 form = AuthenticationForm(data=request.POST, prefix='login')
183 auth.login(request, form.get_user())
184 response_data = {'success': True, 'errors': {}}
186 response_data = {'success': False, 'errors': form.errors}
187 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
190 def book_sets(request, slug):
191 book = get_object_or_404(models.Book, slug=slug)
192 user_sets = models.Tag.objects.filter(category='set', user=request.user)
193 book_sets = book.tags.filter(category='set', user=request.user)
195 if not request.user.is_authenticated():
196 return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
198 if request.method == 'POST':
199 form = forms.ObjectSetsForm(book, request.user, request.POST)
201 book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
202 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
203 if request.is_ajax():
204 return HttpResponse('<p>Półki zostały zapisane.</p>')
206 return HttpResponseRedirect('/')
208 form = forms.ObjectSetsForm(book, request.user)
209 new_set_form = forms.NewSetForm()
211 return render_to_response('catalogue/book_sets.html', locals(),
212 context_instance=RequestContext(request))
215 def fragment_sets(request, id):
216 fragment = get_object_or_404(models.Fragment, pk=id)
217 user_sets = models.Tag.objects.filter(category='set', user=request.user)
218 fragment_sets = fragment.tags.filter(category='set', user=request.user)
220 if not request.user.is_authenticated():
221 return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
223 if request.method == 'POST':
224 form = forms.ObjectSetsForm(fragment, request.user, request.POST)
226 fragment.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
227 list(fragment.tags.filter(~Q(category='set') | ~Q(user=request.user))))
228 if request.is_ajax():
229 return HttpResponse('<p>Półki zostały zapisane.</p>')
231 return HttpResponseRedirect('/')
233 form = forms.ObjectSetsForm(fragment, request.user)
234 new_set_form = forms.NewSetForm()
236 return render_to_response('catalogue/fragment_sets.html', locals(),
237 context_instance=RequestContext(request))
242 def new_set(request):
243 new_set_form = forms.NewSetForm(request.POST)
244 if new_set_form.is_valid():
245 new_set = new_set_form.save(request.user)
247 if request.is_ajax():
248 return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
250 return HttpResponseRedirect('/')
252 return render_to_response('catalogue/book_sets.html', locals(),
253 context_instance=RequestContext(request))
258 def delete_shelf(request, slug):
259 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
262 if request.is_ajax():
263 return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
265 return HttpResponseRedirect('/')
269 def user_shelves(request):
270 shelves = models.Tag.objects.filter(category='set', user=request.user)
271 new_set_form = forms.NewSetForm()
272 return render_to_response('catalogue/user_shelves.html', locals(),
273 context_instance=RequestContext(request))