Exemple #1
0
def update(request, id=None):
	snippet = get_object_or_404(Snippet, pk=id)
	if request.user.id == snippet.author_id:
		if request.method == 'POST': # If the form has been submitted...
			form = SnippetForm(request.POST) # A form bound to the POST data
			if form.is_valid():
				formData = form.save(commit = False)
				formData.pk = snippet.pk
				if 'delete' in request.POST:
					snippet.delete()
					request.session['flash'] = ['#' + str(formData.pk) +' deleted successfuly', 'sucess']
					return HttpResponseRedirect('/accounts/profile/')
				if 'preview' in request.POST:
					data = {}
					data['title'] = formData.title;
					data['preview_body'] = highlight(formData.body, get_lexer_by_name(formData.lexer), HtmlFormatter(cssclass = 'source'))
					data['lines'] = range(1, formData.body.count('\n') + 2)
					data['form'] = form
					data['snippet'] = snippet
					return render_to_response('snippets/process.html', data, context_instance=build_context(request))
				else: #save
					formData.author = request.user
					if not formData.lexer:
						try:
							lexer = guess_lexer(formData.body)
							for lex in LEXERS.itervalues():
								if lexer.name == lex[1]:
									formData.lexer = lex[2][0].lower()
						except ClassNotFound:
							formData.lexer = 'text'
					formData.save()
					if snippet.body != formData.body:
						try:
							last_version = SnippetVersion.objects.order_by('-version').filter(snippet = snippet).all()[0]
							new_version = SnippetVersion(snippet = snippet, version = last_version.version + 1, body = snippet.body)
							new_version.save()
						except:
							create_version = SnippetVersion(snippet = snippet, version = 1, body = snippet.body)
							create_version.save()
					request.session['flash'] = ['#' + str(formData.pk) +' updated successfuly', 'sucess'];
					return HttpResponseRedirect('/accounts/profile/') # Redirect after POST
			else:
			   	return render_to_response('snippets/process.html', {'form': form }, context_instance=build_context(request))
		else:
			form = SnippetForm(instance=snippet)
		return render_to_response('snippets/process.html', {'form': form, 'snippet': snippet }, context_instance=build_context(request))
	else:
		request.session['flash'] = ['Access denied', 'error'];
		return HttpResponseRedirect('/accounts/profile/') # Redirect after POST