Esempio n. 1
0
def pastie_save(req, nosave=False, skin=None):
	"""
	retrieve shell from the form, save or display
	Fix dependency
	"""
	if req.method == 'POST':
		slug = req.POST.get('slug', None)
		if slug:
			" UPDATE - get the instance if slug provided "
			pastie = get_object_or_404(Pastie,slug=slug)
			#pastieform = PastieForm(req.POST, instance=pastieinstance)
		else:	
			" CREATE "
			pastie = Pastie()
			if not nosave:
				" create slug from random string if needed"
				pastie.set_slug()
				if req.user.is_authenticated():
					pastie.author = req.user 
				pastie.save()

		shellform = ShellForm(req.POST)
			
		if shellform.is_valid():
			
			" Instantiate shell data from the form "
			shell = shellform.save(commit=False)

			" Connect shell with pastie "
			shell.pastie = pastie
			
			# add js_dependency
			dependency_ids = [int(dep[1]) for dep in req.POST.items() if dep[0].startswith('js_dependency')]
			dependencies = []
			for dep_id in dependency_ids:
				dep = JSDependency.objects.get(id=dep_id)
				dependencies.append(dep)
			if nosave:
				" return the pastie page only " 
				# no need to connect with pastie
				return pastie_display(req, None, shell, dependencies, skin)

			" add user to shell if anyone logged in "
			if req.user.is_authenticated():
				shell.author = req.user

			if slug:
				shell.set_next_version()
				
			shell.save()
			
			for dep in dependencies:
				shell.js_dependency.add(dep)
		
			" return json with pastie url "
			return HttpResponse(simplejson.dumps({
					#'pastie_url': ''.join(['http://',req.META['SERVER_NAME'], shell.get_absolute_url()]),
					'pastie_url_relative': shell.get_absolute_url()
					}),mimetype='application/javascript'
				)
		else: 
			error = "Shell form does not validate"
			for s in shellform:
				if hasattr(s, 'errors') and s.errors:
					error = error + str(s.__dict__) 
	else: 
		error = 'Please use POST request'
	
	# Report errors
	return HttpResponse(simplejson.dumps({'error':error}),
					mimetype='application/javascript'
	)