PageRenderTime 224ms CodeModel.GetById 100ms app.highlight 14ms RepoModel.GetById 107ms app.codeStats 0ms

/views/snippets.py

http://cab.googlecode.com/
Python | 214 lines | 184 code | 9 blank | 21 comment | 3 complexity | 4b85529ac5295c38da3b90ee1e01246f MD5 | raw file
  1"""
  2Views which work with Snippets, allowing them to be added, modified,
  3rated and viewed according to various criteria.
  4
  5"""
  6
  7from django.http import HttpResponse, HttpResponseRedirect
  8from django.shortcuts import get_object_or_404, render_to_response
  9from django.template import RequestContext
 10from django.views.generic import list_detail
 11from django.contrib.auth.decorators import login_required
 12from django.contrib.auth.models import User
 13from cab import forms
 14from cab.models import Language, Rating, Snippet, Tag
 15from bookmarks import base_generic_dict
 16
 17def add_snippet(request):
 18    """
 19    Allows a user to add a Snippet to the database.
 20    
 21    Context::
 22        form
 23            The form to add the Snippet.
 24    
 25    Template::
 26        cab/add_snippet_form.html
 27    
 28    """
 29    original_id = request.GET.get('oid', None)
 30    
 31    if request.method == 'POST':
 32        form = forms.AddSnippetForm(request.POST)
 33        if form.is_valid():
 34            new_snippet = Snippet(title=form.clean_data['title'],
 35                                  description=form.clean_data['description'],
 36                                  code=form.clean_data['code'],
 37                                  tag_list=form.clean_data['tag_list'],
 38                                  language_id=form.clean_data['language'],
 39                                  author=request.user)
 40            if original_id:
 41                new_snippet.original_id = original_id
 42            new_snippet.save()
 43            return HttpResponseRedirect(new_snippet.get_absolute_url())
 44    else:
 45        form = forms.AddSnippetForm()
 46    return render_to_response('cab/add_snippet_form.html',
 47                              { 'form': form },
 48                              context_instance=RequestContext(request))
 49add_snippet = login_required(add_snippet)
 50
 51def download(request, snippet_id):
 52    """
 53    Allows a user to download a Snippet's code.
 54    
 55    Context::
 56        None, returns a downloadable file.
 57    
 58    Template::
 59        None, returns a downloadable file.
 60    
 61    """
 62    snippet = get_object_or_404(Snippet, pk=snippet_id)
 63    response = HttpResponse(snippet.code, mimetype='text/plain')
 64    response['Content-Disposition'] = 'attachment; filename=%s.%s' % (snippet.id,
 65                                                                      snippet.language.file_extension)
 66    response['Content-Type'] = snippet.language.mime_type
 67    return response
 68
 69def edit_snippet(request, snippet_id):
 70    """
 71    Allows a user to edit an existing Snippet.
 72    
 73    Context::
 74        form
 75            The form to add the Snippet.
 76    
 77        original
 78            The Snippet being edited.
 79    
 80    Template::
 81        cab/edit_snippet_form.html
 82    
 83    """
 84    snippet = get_object_or_404(Snippet,
 85                                pk=snippet_id,
 86                                author__pk=request.user.id)
 87    if request.method == 'POST':
 88        form = forms.EditSnippetForm(request.POST)
 89        if form.is_valid():
 90            for field in ['title', 'description', 'code', 'tag_list']:
 91                setattr(snippet, field, form.clean_data[field])
 92            snippet.save()
 93            return HttpResponseRedirect(snippet.get_absolute_url())
 94    else:
 95        form = forms.EditSnippetForm(snippet.__dict__)
 96    return render_to_response('cab/edit_snippet_form.html',
 97                              { 'form': form,
 98                                'original': snippet },
 99                              context_instance=RequestContext(request))
100edit_snippet = login_required(edit_snippet)
101
102def rate_snippet(request, snippet_id):
103    """
104    Allows a user to rate a Snippet.
105    
106    Context::
107        None, returns a redirect back to the Snippet.
108    
109    Template::
110        None, returns a redirect back to the Snippet.
111    
112    """
113    snippet = get_object_or_404(Snippet, pk=snippet_id)
114    
115    if not Rating.objects.already_rated(request.user.id, snippet.id):
116        score = request.GET.get('score')
117        if score:
118            rating = Rating.objects.create(snippet=snippet,
119                                           user=request.user,
120                                           score={ 'up': 1,
121                                                   'down': -1 }[score])
122    return HttpResponseRedirect(snippet.get_absolute_url())
123rate_snippet = login_required(rate_snippet)
124
125def snippets_by_author(request, username):
126    """
127    List of Snippets submitted by a particular User.
128    
129    Context::
130    Same as the generic ``list_detail.object_list`` view, with
131    one extra variable:
132    
133        object
134            The User
135    
136    Template::
137        cab/user_detail.html
138    
139    """
140    user = get_object_or_404(User, username__exact=username)
141    return list_detail.object_list(request,
142                                   queryset=Snippet.objects.get_by_author(user.username),
143                                   extra_context={ 'object': user },
144                                   template_name='cab/user_detail.html',
145                                   **base_generic_dict)
146
147def snippets_by_language(request, slug):
148    """
149    List of Snippets written in a particular Language.
150    
151    Context::
152    Same as the generic ``list_detail.object_list`` view, with
153    one extra variable:
154    
155        object
156            The Language
157    
158    Template::
159        cab/language_detail.html
160    
161    """
162    language = get_object_or_404(Language, slug__exact=slug)
163    return list_detail.object_list(request,
164                                   queryset=Snippet.objects.get_by_language(slug),
165                                   extra_context={ 'object': language },
166                                   template_name='cab/language_detail.html',
167                                   **base_generic_dict)
168
169def snippets_by_tag(request, slug):
170    """
171    List of Snippets with a particular Tag.
172    
173    Context::
174    Same as the generic ``list_detail.object_list`` view, with
175    one extra variable:
176    
177        object
178            The Tag
179    
180    Template::
181        cab/tag_detail.html
182    
183    """
184    tag = get_object_or_404(Tag, slug__exact=slug)
185    return list_detail.object_list(request,
186                                   queryset=Snippet.objects.get_by_tag(slug),
187                                   extra_context={ 'object': tag },
188                                   template_name='cab/tag_detail.html',
189                                   **base_generic_dict)
190
191def snippet_detail(request, snippet_id):
192    """
193    Detail view of a Snippet.
194    
195    Context::
196        object
197            The Snippet object.
198    
199        num_ratings
200            The number of Ratings this Snippet has received.
201    
202        rating_score
203            The sum of this Snippet's received ratings.
204    
205    Template::
206        cab/snippet_detail.html
207    
208    """
209    snippet = get_object_or_404(Snippet, pk=snippet_id)
210    return render_to_response('cab/snippet_detail.html',
211                              { 'object': snippet,
212                                'num_ratings': snippet.rating_set.count(),
213                                'rating_score': Rating.objects.score_for_snippet(snippet.id) },
214                              context_instance=RequestContext(request))