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_GET, 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
16 class LazyEncoder(simplejson.JSONEncoder):
17 def default(self, obj):
18 if isinstance(obj, Promise):
19 return force_unicode(obj)
23 from catalogue import models
24 from catalogue import forms
25 from catalogue.utils import split_tags
28 def catalogue_redirect(request, tags=''):
29 if len(request.GET['q']) > 0:
31 tag = models.Tag.objects.get(name=request.GET['q'])
34 tags = tags + tag.slug
35 except models.Tag.DoesNotExist:
36 book = get_object_or_404(models.Book, title=request.GET['q'])
37 return HttpResponseRedirect(book.get_absolute_url())
39 return HttpResponseRedirect(reverse('catalogue.views.tagged_book_list', kwargs=dict(tags=tags)))
41 return HttpResponseRedirect(reverse('catalogue.views.main_page'))
44 def tags_starting_with(request):
46 prefix = request.GET['q']
50 books = models.Book.objects.filter(title__icontains=prefix)
51 tags = models.Tag.objects.filter(name__icontains=prefix)
52 if request.user.is_authenticated():
53 tags = tags.filter(~Q(category='set') | Q(user=request.user))
55 tags = tags.filter(~Q(category='set'))
57 completions = [book.title for book in books] + [tag.name for tag in tags]
59 return HttpResponse('\n'.join(completions))
62 return HttpResponse('')
65 def main_page(request):
66 if 'q' in request.GET:
67 return catalogue_redirect(request)
69 if request.user.is_authenticated():
70 extra_where = '(NOT catalogue_tag.category = "set" OR catalogue_tag.user_id = %d)' % request.user.id
72 extra_where = 'NOT catalogue_tag.category = "set"'
73 tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
74 categories = split_tags(tags)
76 form = forms.SearchForm()
77 return render_to_response('catalogue/main_page.html', locals(),
78 context_instance=RequestContext(request))
81 def book_list(request):
82 if 'q' in request.GET:
83 return catalogue_redirect(request)
85 books = models.Book.objects.all()
86 form = forms.SearchForm()
88 books_by_first_letter = SortedDict()
90 books_by_first_letter.setdefault(book.title[0], []).append(book)
92 return render_to_response('catalogue/book_list.html', locals(),
93 context_instance=RequestContext(request))
96 def tagged_book_list(request, tags=''):
97 if 'q' in request.GET:
98 return catalogue_redirect(request, tags)
100 choices_split = tags.split('/')
102 for tag in choices_split:
103 tag = get_object_or_404(models.Tag, slug=tag)
104 if tag.category == 'set' and (not request.user.is_authenticated() or request.user != tag.user):
108 books = models.Book.objects.with_all(tags)
110 if request.user.is_authenticated():
111 extra_where = '(NOT catalogue_tag.category = "set" OR catalogue_tag.user_id = %d)' % request.user.id
113 extra_where = 'NOT catalogue_tag.category = "set"'
114 related_tags = models.Tag.objects.related_for_model(tags, models.Book, counts=True, extra={'where': [extra_where]})
115 categories = split_tags(related_tags)
117 form = forms.SearchForm()
119 return render_to_response('catalogue/tagged_book_list.html', dict(
123 categories=categories,
124 ), context_instance=RequestContext(request))
127 def book_detail(request, slug):
128 book = get_object_or_404(models.Book, slug=slug)
129 tags = list(book.tags.filter(~Q(category='set')))
130 categories = split_tags(tags)
131 search_form = forms.SearchForm()
133 return render_to_response('catalogue/book_detail.html', locals(),
134 context_instance=RequestContext(request))
137 def logout_then_redirect(request):
139 return HttpResponseRedirect(request.GET.get('next', '/'))
143 def register(request):
144 registration_form = UserCreationForm(request.POST, prefix='registration')
145 if registration_form.is_valid():
146 user = registration_form.save()
147 user = auth.authenticate(
148 username=registration_form.cleaned_data['username'],
149 password=registration_form.cleaned_data['password1']
151 auth.login(request, user)
152 response_data = {'success': True, 'errors': {}}
154 response_data = {'success': False, 'errors': registration_form.errors}
155 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
160 form = AuthenticationForm(data=request.POST, prefix='login')
162 auth.login(request, form.get_user())
163 response_data = {'success': True, 'errors': {}}
165 response_data = {'success': False, 'errors': form.errors}
166 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
170 def book_sets(request, slug):
171 book = get_object_or_404(models.Book, slug=slug)
172 user_sets = models.Tag.objects.filter(category='set', user=request.user)
173 book_sets = book.tags.filter(category='set', user=request.user)
175 if request.method == 'POST':
176 form = forms.BookSetsForm(book, request.user, request.POST)
178 book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
179 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
180 if request.is_ajax():
181 return HttpResponse('<p>Zestawy zostały zapisane</p>')
183 return HttpResponseRedirect('/')
185 form = forms.BookSetsForm(book, request.user)
186 new_set_form = forms.NewSetForm()
188 return render_to_response('catalogue/book_sets.html', locals(),
189 context_instance=RequestContext(request))
194 def new_set(request):
195 new_set_form = forms.NewSetForm(request.POST)
196 if new_set_form.is_valid():
197 new_set = new_set_form.save(request.user)
198 return HttpResponse('<p>Zestaw <strong>%s</strong> został utworzony</p>' % new_set)
200 return render_to_response('catalogue/book_sets.html', locals(),
201 context_instance=RequestContext(request))