Ejemplo n.º 1
0
def save_event(request):
	if request.is_ajax() or True:
		print 'Is AJAX'
		# TODO: Add handler for these below. They are required and must be submitted or else the form will not validate. Or perhaps the clean_fields() exception is enough...?
		import pprint
		print 'Hér kemur hrátt data:'
		pprint.pprint(request.POST['data'])
		print 'Hér kemur JSON útgáfan:'
		data = json.loads(request.POST['data'])
		pprint.pprint(data)
		t = data['title']
		d = data['description']
		dtb = timezone.make_aware(parser.parse(data['date_time_begin']),timezone.get_default_timezone())
		dte = timezone.make_aware(parser.parse(data['date_time_end']),timezone.get_default_timezone())
		et_id = data['event_type']
		try:
			event_id = data['event_id']
			if event_id == '':
			# If no event id has been supplied, we'll create a new event.
				event = Event(title=t, description=d, date_time_begin=dtb, date_time_end=dte, event_type_id=et_id)
			else:
			# else we update the existing one.
				event = Event.objects.get(pk=event_id)
				event.title = t
				event.description = d
				event.date_time_begin = dtb
				event.date_time_end = dte
				event.event_type_id = et_id
				#return HttpResponse('Event fields updated.')
			# Now save the event
			try:
				event.clean_fields()
				event.save()
				print 'The event is: ------'
				print (vars(event))
				print '--------------------'
			except:
				return HttpResponse ("Hello, world. Could not save event.")

			# Now that the event has been taken care of, let's sort out the event roles etc.
			# Flow:
			# For each role:
			for role in Role.objects.all():
				print 'Role ID %s' % role.id
				print 'Role is %s' % role
				try: #if we want the role:
					currentparticipants = [] # This will be populated below if the event exists (and currently has any participants).
					currentgroups = [] # This will be populated below if the event exists (and currently has any participants).
					currentmembers= [] # This will be populated below if the event exists (and currently has any participants).

					wantedparticipantIDs = data['role'][role.id]['participants']
					print 'Wanted participantsID: {}'.format(wantedparticipantIDs)
					wantedgroups = [Group.objects.get(pk=int(groupid[1:])) for groupid in wantedparticipantIDs if groupid[0]=='g']
					print 'We want event role {} with groups {}'.format(role, wantedgroups)
					wantedmembers= [Member.objects.get(pk=int(memberid[1:])) for memberid in wantedparticipantIDs if memberid[0]=='m']
					print 'We want event role {} with members {}'.format(role, wantedmembers)
					try: #check whether the EventRole already exists
						# In the event that an EventRole already exists, we have to:
						#  1. Get the EventRole, stored in eventrole.
						#  2. Remove unwanted participants
						# Adding wanted participants is shared with EventRoles that
						# need to be created so we're doing that later on.
						#  3. Update the minimum and maximum number of participants

						# 1.
						eventrole = EventRole.objects.get(event_id=event.id,role_id=role.id)
						print 'EventRole "{}" already exists.'.format(eventrole)

						# 2.
						#currentgroups= GroupInvitation.objects.filter(event_role=eventrole)
						currentgroups = eventrole.invited_groups.all()
						currentmembers= eventrole.invited_members.all()
						print 'currentgroups: {}'.format(currentgroups)
						print 'currentmembers: {}'.format(currentmembers)
						print 'EventRole already has these invitations:'
						for group in currentgroups:
							print '>>{} ({})'.format(group, group.id)
							#print 'Comare {} with {}'.format(group.id,wantedgroups)
							if group not in wantedgroups:
								print '-- ID is {}: We don\'t want {}.'.format(group.id,group)
								#gi = GroupInvitation(event_role=eventrole,group=group)
								#print 'Removing group {} from eventrole {}'.format(group,eventrole)
								#print 'DEBUG'
								try:
									print 'DEBUG: {}'.format(eventrole.invited_groups)
									gi = GroupInvitation.objects.get(event_role=eventrole,group=group)
									#print gi
									gi.delete()
									print 'BINGO'
								except:
									print 'Could not remove group {} from {}'.format(group,currentgroups)
							else:
								print '++ ID is {}: We keep {}.'.format(group.id,group)
						for member in currentmembers:
							print '>>{} ({})'.format(member, member.id)
							if member not in wantedmembers:
								print '-- ID is {}: We don\'t want {}.'.format(member.id,member)
								try:
									print 'DEBUG: {}'.format(eventrole.invited_members)
									mi = MemberInvitation.objects.get(event_role=eventrole,member=member)
									#print mi
									mi.delete()
									print 'BINGO'
								except:
									print 'Could not remove member {} from {}'.format(member,currentmembers)
							else:
								print '++ ID is {}: We keep {}.'.format(member.id,member)
						# 3.
						if eventrole.minimum != int(data['role'][role.id]['min']) or eventrole.maximum != int(data['role'][role.id]['max']):
							eventrole.minimum = int(data['role'][role.id]['min'])
							eventrole.maximum = int(data['role'][role.id]['max'])
							try:
								eventrole.clean_fields()
								eventrole.save()
								print 'eventrole saved: {}.'.format(eventrole)
							except:
								return HttpResponse('Hello, world. Could not update eventrole max/min numbers.')
					except: #else
						# Since there is no existing EventRole, we need to:
						#  1. Create an EventRole, and save it as eventrole.
						# and that's it! Adding participants is done below for both
						# existing and recently created EventRoles.
						eventrole = EventRole(event_id=event.id,role_id=role.id,minimum=int(data['role'][role.id]['min']), maximum=int(data['role'][role.id]['max']))
						print 'No EventRole exists, creating {}.'.format(eventrole)
						try:
							eventrole.clean_fields()
							eventrole.save()
							print 'eventrole saved: {}.'.format(eventrole)
						except:
							return HttpResponse('Hello, world. Could not save eventrole.')

					# Now that we have the eventrole and it has been stripped of its
					# unwanted participatns, let's add the wanted ones.
					# Workflow:
					# For each wanted participant,
					#   if they're not currently invited,
					#     create a GroupInvitation and attach it to the EventRole

					# For each participant
					print 'Adding invitations:'
					print 'Wanted groups: {}'.format(wantedgroups)
					print 'Wanted members: {}'.format(wantedmembers)
					for group in wantedgroups:
						print '>>{} ({})'.format(group, group.id)
						if group not in currentgroups:
							print '++ Group {} is not invited: Create GroupInvitation!'.format(group)
							gi = GroupInvitation(event_role=eventrole, group=group)
							print '++ GroupInvitation created: '.format(gi)
							try:
								gi.clean_fields()
								gi.save()
								print '++ GroupInvitation saved'
							except:
								print 'ERROR: Could not save GroupInvitation {}'.format(gi)
						else:
							print '.. Group {} already invited: nothing to do. :-)'.format(group)
					print 'Groups done!'
					for member in wantedmembers:
						print '>>{} ({})'.format(member, member.id)
						if member not in currentmembers:
							print '++ Member {} is not invited: Create MemberInvitation!'.format(member)
							mi = MemberInvitation(event_role=eventrole, member=member)
							print '++ MemberInvitation created: '.format(mi)
							try:
								mi.clean_fields()
								mi.save()
								print '++ MemberInvitation saved'
							except:
								print 'ERROR: Could not save MemberInvitation {}'.format(mi)
						else:
							print '.. Member {} already invited: nothing to do. :-)'.format(member)
					print 'All done!'
				except: #if we don't want the role:
					print 'No role wanted.'
					try: # check if the role exists and must be removed
						eventrole = EventRole.objects.get(event__id=event.id,role__id=role.id)
						print 'Removing eventrole: %s' % eventrole
						eventrole.delete()
					except: # No role wanted. No role exists. All good.
						print 'No role exists. All good.'
				print ' ..... '
		except:
			return HttpResponse("Hello, world. Could not create event.")
		return HttpResponse(event.id)
	else:
		return HttpResponse("Hello, world. Not AJAX request.")
Ejemplo n.º 2
0
Archivo: views.py Proyecto: aucms/tsar
def save_event(request):
	print 'Saving event'
	if not request.is_ajax():
		return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Hello, world. Not an AJAX request.'}))
	else:
		print 'Is AJAX'
		import pprint
		print 'Hér kemur hrátt data:'
		pprint.pprint(request.POST['data'])
		print 'Hér kemur JSON útgáfan:'
		data = json.loads(request.POST['data'])
		pprint.pprint(data)

		# Sanitise some of the data and return messages if it fails.

		### TITLE ###
		# The title must be non-zero and no longer than 64 characters (defined in events/models.py).
		print 'Submitted data:'
		t = data['title']
		if t == "":
			return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Title missing.', }))
		elif len(t) > 64:
			return HttpResponse(json.dumps({ 'type': 'error', 'message': 'The title is currently '+str(len(t))+' characters long but the maximum is 64.', }))
		import sys
		print sys.stdout.encoding
		print type(t)
		print '--title: {}'.format(t.encode('UTF-8'))

		### DESCRIPTION ###
		# There are no restrictions on the description field other than being cleaned. It may be blank and arbitrarily long.
		d = data['description']
		# The dates must be supplied and the beginning must precede the end.
		print '--description: {}'.format(d.encode('UTF-8'))

		### DATES ###
		if data['date_time_begin'] == "":
			return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Beginning date missing.', }))
		try:
			dtb = timezone.make_aware(parser.parse(data['date_time_begin']),timezone.get_default_timezone())
		except:
			return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Beginning date-time is not a valid datetime.', }))
		print '--begins: {}'.format(dtb)
		if data['date_time_end'] == "":
			return HttpResponse(json.dumps({ 'type': 'error', 'message': 'End date missing.', }))
		try:
			dte = timezone.make_aware(parser.parse(data['date_time_end']),timezone.get_default_timezone())
		except:
			return HttpResponse(json.dumps({ 'type': 'error', 'message': 'End date-time is not a valid datetime', }))
		if dte <= dtb:
			return HttpResponse(json.dumps({ 'type': 'error', 'message': 'The event start time must precede the end.', }))
		print '--ends: {}'.format(dte)

		### TYPE ###
		# The event-type must be supplied.
		et_id = data['event_type']
		print '--type ID: {}'.format(et_id)
		if et_id== "":
			return HttpResponse(json.dumps({ 'type': 'error', 'message': 'No event type supplied.', }))

		### EVENT ID ###
		print 'All the data has been submitted. Checking whether event_id has been supplied.'
		try:
			event_id = data['event_id']
			print 'event_id: {}'.format(event_id)
		except:
			return HttpResponse(json.dumps({ 'type': 'error', 'message': 'No event_id submitted.', }))
		if event_id == '':
			# If no event id has been supplied, we'll create a new event.
			print 'Creating event...'
			event = Event(title=t, description=d, date_time_begin=dtb, date_time_end=dte, event_type_id=et_id)
		else:
			# else we update the existing one.
			print 'Updating event...'
			event = Event.objects.get(pk=event_id)
			event.title = t
			event.description = d
			event.date_time_begin = dtb
			event.date_time_end = dte
			event.event_type_id = et_id

		# Now save the event
		try:
			event.clean_fields()
			event.save()
			print 'The event is: ------'
			pprint.pprint(vars(event))
			print '--------------------'
		except:
			return HttpResponse (json.dumps({ 'type': 'error', 'message': 'Could not save event.'}))

		# Now that the event has been taken care of, let's sort out the event roles etc.
		# Flow:
		# For each role:
		for role in Role.objects.all():
			print 'Role ID %s' % role.id
			print 'Role is %s' % role
			try:
				participants_exist = data['role'][role.id]['participants']
			except:
				participants_exist = False
			#print participants_exist
			if participants_exist:
				# If we want eventroles, check whether these need to be created and otherwise update them.

				currentparticipants = [] # This will be populated below if the event exists (and currently has any participants).
				currentgroups = [] # This will be populated below if the event exists (and currently has any participants).
				currentmembers= [] # This will be populated below if the event exists (and currently has any participants).

				# The wantedparticipantIDs is a list of invitations compiled from a
				# drop-down in the interface. the drop-down contains positions,
				# groups, members and the option to make it an open event (inviting
				# all members). To differentiate between the primary keys of
				# positions, groups and members, these are prefixed with the
				# characters 'p', 'g' and 'm', respectively.

				wantedparticipantIDs = data['role'][role.id]['participants']
				print 'Wanted participantsID: {}'.format(wantedparticipantIDs)

				wantedpositions = [Position.objects.get(pk=int(positionid[1:])) for positionid in wantedparticipantIDs if positionid[0]=='p']
				print 'We want event role {} with positions {}'.format(role, wantedpositions)
				wantedgroups = [Group.objects.get(pk=int(groupid[1:])) for groupid in wantedparticipantIDs if groupid[0]=='g']
				print 'We want event role {} with groups {}'.format(role, wantedgroups)
				wantedmembers= [Member.objects.get(pk=int(memberid[1:])) for memberid in wantedparticipantIDs if memberid[0]=='m']
				print 'We want event role {} with members {}'.format(role, wantedmembers)

				# Check whether the event is open.
				is_open = ('a' in wantedparticipantIDs)

				# Workflow:
				#  1. Get or create the EventRole.
				#  2. Remove unwanted invitations.
				#  3. Update the minimum and maximum number of participants.
				#  4. Adding wanted invitations

				try: # check whether the EventRole already exists
					# 1. Get the EventRole, stored in eventrole.
					eventrole = EventRole.objects.get(event_id=event.id,role_id=role.id)
					print 'EventRole "{}" already exists.'.format(eventrole)
				except:
					# Since there is no existing EventRole, we need to:
					#  1. Create an EventRole, and save it as eventrole.
					# and that's it! Adding participants is done below for both
					# existing and recently created EventRoles.
					try:
						print 'event_id: {}'.format(event.id)
						print 'role_id: {}'.format(role.id)
						# TODO: Later feature...
						#eventrole = EventRole(event_id=event.id,role_id=role.id,minimum=int(data['role'][role.id]['min']), maximum=int(data['role'][role.id]['max']))
						eventrole = EventRole(event_id=event.id,role_id=role.id,is_open=is_open)
						print 'No EventRole exists, creating {}.'.format(eventrole)
					except:
						print 'Could not create eventrole.'
						return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not create eventrole.' }))
					try:
						eventrole.clean_fields()
						eventrole.save()
						print 'eventrole saved: {}.'.format(eventrole)
					except:
						return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not save eventrole.' }))

				# 2. Remove unwanted invitations.
				currentpositions = eventrole.invited_positions.all()
				currentgroups = eventrole.invited_groups.all()
				currentmembers= eventrole.invited_members.all()
				print 'currentpositions: {}'.format(currentpositions)
				print 'currentgroups: {}'.format(currentgroups)
				print 'currentmembers: {}'.format(currentmembers)
				print 'EventRole already has these invitations:'
				for position in currentpositions:
					print '>>{} ({})'.format(position, position.id)
					if position not in wantedpositions:
						print '-- ID is {}: We don\'t want {}.'.format(group.id,group)
						try:
							#print 'DEBUG: {}'.format(eventrole.invited_positions)
							pi = PositionInvitation.objects.get(event_role=eventrole,position=position)
							pi.delete()
						except:
							print 'Could not remove position {} from {}'.format(group,currentgroups)
							return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not remove position '+str(position)+' from '+currentpositions+'.' }))
					else:
						print '++ ID is {}: We keep position {}.'.format(position.id,position)
				for group in currentgroups:
					print '>>{} ({})'.format(group, group.id)
					if group not in wantedgroups:
						print '-- ID is {}: We don\'t want {}.'.format(group.id,group)
						try:
							#print 'DEBUG: {}'.format(eventrole.invited_groups)
							gi = GroupInvitation.objects.get(event_role=eventrole,group=group)
							gi.delete()
						except:
							print 'Could not remove group {} from {}'.format(group,currentgroups)
							return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not remove group '+str(group)+' from '+currentgroups+'.' }))
					else:
						print '++ ID is {}: We keep group {}.'.format(group.id,group)
				for member in currentmembers:
					print '>>{} ({})'.format(member, member.id)
					if member not in wantedmembers:
						print '-- ID is {}: We don\'t want {}.'.format(member.id,member)
						try:
							#print 'DEBUG: {}'.format(eventrole.invited_members)
							mi = MemberInvitation.objects.get(event_role=eventrole,member=member)
							mi.delete()
						except:
							print 'Could not remove member {} from {}'.format(member,currentmembers)
							return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not remove member '+str(member)+' from '+currentmembers+'.' }))
					else:
						print '++ ID is {}: We keep member {}.'.format(member.id,member)

				# Finally set whether the EventRole is open to all members:
				eventrole.is_open = is_open
				try:
					eventrole.clean_fields()
					eventrole.save()
					print 'eventrole saved: {}.'.format(eventrole)
				except:
					return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not update whether the EventRole is open numbers.' }))

				# 3. Update the minimum and maximum number of participants.
				# TODO: Later feature...
				#if eventrole.minimum != int(data['role'][role.id]['min']) or eventrole.maximum != int(data['role'][role.id]['max']):
				#	eventrole.minimum = int(data['role'][role.id]['min'])
				#	eventrole.maximum = int(data['role'][role.id]['max'])
				#	try:
				#		eventrole.clean_fields()
				#		eventrole.save()
				#		print 'eventrole saved: {}.'.format(eventrole)
				#	except:
				#		return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not update eventrole max/min numbers.' }))

				# 4. Adding wanted invitations
				# Now that we have the eventrole and it has been stripped of its
				# unwanted participatns, let's add the wanted ones.
				# Workflow:
				# For each wanted participant,
				#   if they're not currently invited,
				#     create a {Position,Group,Member}Invitation and attach it to the EventRole

				# For each participant
				print 'Adding invitations:'
				print 'Wanted positions: {}'.format(wantedpositions)
				print 'Wanted groups: {}'.format(wantedgroups)
				print 'Wanted members: {}'.format(wantedmembers)
				for position in wantedpositions:
					print '>>{} ({})'.format(position, position.id)
					if position not in currentpositions:
						print '++ Position {} is not invited: Create PositionInvitation!'.format(position)
						print eventrole
						print position
						pi = PositionInvitation(event_role=eventrole, position=position)
						print '++ PositionInvitation created: '.format(pi)
						try:
							pi.clean_fields()
							pi.save()
							print '++ PositionInvitation saved'
						except:
							print 'ERROR: Could not save PositionInvitation {}'.format(pi)
							return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not save PositionInvitation '+pi+'.' }))
					else:
						print '.. Position {} already invited: nothing to do. :-)'.format(position)
				print 'Positions done!'
				for group in wantedgroups:
					print '>>{} ({})'.format(group, group.id)
					if group not in currentgroups:
						print '++ Group {} is not invited: Create GroupInvitation!'.format(group)
						gi = GroupInvitation(event_role=eventrole, group=group)
						print '++ GroupInvitation created: '.format(gi)
						try:
							gi.clean_fields()
							gi.save()
							print '++ GroupInvitation saved'
						except:
							print 'ERROR: Could not save GroupInvitation {}'.format(gi)
							return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not save GroupInvitation '+gi+'.' }))
					else:
						print '.. Group {} already invited: nothing to do. :-)'.format(group)
				print 'Groups done!'
				for member in wantedmembers:
					print '>>{} ({})'.format(member, member.id)
					if member not in currentmembers:
						print '++ Member {} is not invited: Create MemberInvitation!'.format(member)
						mi = MemberInvitation(event_role=eventrole, member=member)
						print '++ MemberInvitation created: '.format(mi)
						try:
							mi.clean_fields()
							mi.save()
							print '++ MemberInvitation saved'
						except:
							print 'ERROR: Could not save MemberInvitation {}'.format(mi)
							return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not save MemberInvitation '+mi+'.' }))
					else:
						print '.. Member {} already invited: nothing to do. :-)'.format(member)
				print 'All done!'
			else: #if we don't want the role:
				print 'No role wanted.'
				try: # check if the role exists and must be removed
					eventrole = EventRole.objects.get(event__id=event.id,role__id=role.id)
					print 'Removing eventrole: %s' % eventrole
					eventrole.delete()
				except: # No role wanted. No role exists. All good.
					print 'No role exists. All good.'
			print ' ..... '

		# for current tags:
		#	if tag not in submitted data:
		#		delete eventtag(event=event,tag=tag)
		# for all TagTypes:
		#	for submitted tags:
		#		if tag not currently saved:
		#			create eventtag(event=event,tag=tag)
		print 'Do tags.'
		print TagType.objects.all()

		print 'Iterate over eventtags'
		for tag in event.tags.all():
			try:
				print 'trying'
				tagslist=data['tag_type'][tagtype.id]
				#if tagslist == None:
				#	tagslist=[]
				#else:
				#	tagslist='hi'
				print 'tried'
			except:
				print 'excepting'
				tagslist=[]
				print 'excepted'
			print 'tagslist: '+str(tagslist)
			if str(tag.id) not in tagslist:
				print 'tag id '+str(tag.id)+' is not in '+str(data['tag_type'][tag.tag_type.id])
				print 'delete eventtag(event=event,tag='+str(tag)+')'
				try:
					et=EventTag.objects.get(event=event,tag=tag)
				except:
					print 'Could not get EventTag.'
					return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not get EventTag.' }))
				try:
					et.delete()
				except:
					print 'Could not delete EventTag.'
					return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not delete EventTag '+et+'.' }))
			else:
				print 'tag id '+str(tag.id)+' is in '+str(data['tag_type'][tag.tag_type.id])
				print 'Do nothing...'
		print 'Iterate over tagtypes'
		for tagtype in TagType.objects.all():
			if event.event_type in tagtype.event_type.all():
				print tagtype
				print tagtype.id
				try:
					print 'I am trying'
					tagslist=data['tag_type'][tagtype.id]
					print tagslist
					if tagslist == None:
						tagslist=[]
					print 'I tried'
				except:
					print 'I am excepting'
					tagslist=[]
					print 'I have excepted'
				print 'tagslist: '+str(tagslist)
				for tag_id in tagslist:
					tag=Tag.objects.get(pk=tag_id)
					print tag
					if tag not in event.tags.all():
						print 'tag '+str(tag)+' is not in '+str(event.tags.all())
						print 'create eventtag(event=event,tag='+str(tag)+')'
						try:
							et=EventTag(event=event,tag=tag)
						except:
							print 'Could not create EventTag.'
							return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not create EventTag.' }))
						try:
							et.clean_fields()
							et.save()
						except:
							print 'Could not save EventTag.'
							return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not save EventTag '+et+'.' }))
					else:
						print 'tag '+str(tag)+' is already in '+str(event.tags.all())
						print 'Nothing to do...'
			else:
				print 'tagtype '+str(tagtype)+' is not valid for this event'

		return HttpResponse(json.dumps({ 'type': 'success', 'event_id': event.id }))
Ejemplo n.º 3
0
Archivo: views.py Proyecto: aucms/tsar
def save_event(request):
    print 'Saving event'
    if not request.is_ajax():
        return HttpResponse(
            json.dumps({
                'type': 'error',
                'message': 'Hello, world. Not an AJAX request.'
            }))
    else:
        print 'Is AJAX'
        import pprint
        print 'Hér kemur hrátt data:'
        pprint.pprint(request.POST['data'])
        print 'Hér kemur JSON útgáfan:'
        data = json.loads(request.POST['data'])
        pprint.pprint(data)

        # Sanitise some of the data and return messages if it fails.

        ### TITLE ###
        # The title must be non-zero and no longer than 64 characters (defined in events/models.py).
        print 'Submitted data:'
        t = data['title']
        if t == "":
            return HttpResponse(
                json.dumps({
                    'type': 'error',
                    'message': 'Title missing.',
                }))
        elif len(t) > 64:
            return HttpResponse(
                json.dumps({
                    'type':
                    'error',
                    'message':
                    'The title is currently ' + str(len(t)) +
                    ' characters long but the maximum is 64.',
                }))
        import sys
        print sys.stdout.encoding
        print type(t)
        print '--title: {}'.format(t.encode('UTF-8'))

        ### DESCRIPTION ###
        # There are no restrictions on the description field other than being cleaned. It may be blank and arbitrarily long.
        d = data['description']
        # The dates must be supplied and the beginning must precede the end.
        print '--description: {}'.format(d.encode('UTF-8'))

        ### DATES ###
        if data['date_time_begin'] == "":
            return HttpResponse(
                json.dumps({
                    'type': 'error',
                    'message': 'Beginning date missing.',
                }))
        try:
            dtb = timezone.make_aware(parser.parse(data['date_time_begin']),
                                      timezone.get_default_timezone())
        except:
            return HttpResponse(
                json.dumps({
                    'type':
                    'error',
                    'message':
                    'Beginning date-time is not a valid datetime.',
                }))
        print '--begins: {}'.format(dtb)
        if data['date_time_end'] == "":
            return HttpResponse(
                json.dumps({
                    'type': 'error',
                    'message': 'End date missing.',
                }))
        try:
            dte = timezone.make_aware(parser.parse(data['date_time_end']),
                                      timezone.get_default_timezone())
        except:
            return HttpResponse(
                json.dumps({
                    'type': 'error',
                    'message': 'End date-time is not a valid datetime',
                }))
        if dte <= dtb:
            return HttpResponse(
                json.dumps({
                    'type':
                    'error',
                    'message':
                    'The event start time must precede the end.',
                }))
        print '--ends: {}'.format(dte)

        ### TYPE ###
        # The event-type must be supplied.
        et_id = data['event_type']
        print '--type ID: {}'.format(et_id)
        if et_id == "":
            return HttpResponse(
                json.dumps({
                    'type': 'error',
                    'message': 'No event type supplied.',
                }))

        ### EVENT ID ###
        print 'All the data has been submitted. Checking whether event_id has been supplied.'
        try:
            event_id = data['event_id']
            print 'event_id: {}'.format(event_id)
        except:
            return HttpResponse(
                json.dumps({
                    'type': 'error',
                    'message': 'No event_id submitted.',
                }))
        if event_id == '':
            # If no event id has been supplied, we'll create a new event.
            print 'Creating event...'
            event = Event(title=t,
                          description=d,
                          date_time_begin=dtb,
                          date_time_end=dte,
                          event_type_id=et_id)
        else:
            # else we update the existing one.
            print 'Updating event...'
            event = Event.objects.get(pk=event_id)
            event.title = t
            event.description = d
            event.date_time_begin = dtb
            event.date_time_end = dte
            event.event_type_id = et_id

        # Now save the event
        try:
            event.clean_fields()
            event.save()
            print 'The event is: ------'
            pprint.pprint(vars(event))
            print '--------------------'
        except:
            return HttpResponse(
                json.dumps({
                    'type': 'error',
                    'message': 'Could not save event.'
                }))

        # Now that the event has been taken care of, let's sort out the event roles etc.
        # Flow:
        # For each role:
        for role in Role.objects.all():
            print 'Role ID %s' % role.id
            print 'Role is %s' % role
            try:
                participants_exist = data['role'][role.id]['participants']
            except:
                participants_exist = False
            #print participants_exist
            if participants_exist:
                # If we want eventroles, check whether these need to be created and otherwise update them.

                currentparticipants = [
                ]  # This will be populated below if the event exists (and currently has any participants).
                currentgroups = [
                ]  # This will be populated below if the event exists (and currently has any participants).
                currentmembers = [
                ]  # This will be populated below if the event exists (and currently has any participants).

                # The wantedparticipantIDs is a list of invitations compiled from a
                # drop-down in the interface. the drop-down contains positions,
                # groups, members and the option to make it an open event (inviting
                # all members). To differentiate between the primary keys of
                # positions, groups and members, these are prefixed with the
                # characters 'p', 'g' and 'm', respectively.

                wantedparticipantIDs = data['role'][role.id]['participants']
                print 'Wanted participantsID: {}'.format(wantedparticipantIDs)

                wantedpositions = [
                    Position.objects.get(pk=int(positionid[1:]))
                    for positionid in wantedparticipantIDs
                    if positionid[0] == 'p'
                ]
                print 'We want event role {} with positions {}'.format(
                    role, wantedpositions)
                wantedgroups = [
                    Group.objects.get(pk=int(groupid[1:]))
                    for groupid in wantedparticipantIDs if groupid[0] == 'g'
                ]
                print 'We want event role {} with groups {}'.format(
                    role, wantedgroups)
                wantedmembers = [
                    Member.objects.get(pk=int(memberid[1:]))
                    for memberid in wantedparticipantIDs if memberid[0] == 'm'
                ]
                print 'We want event role {} with members {}'.format(
                    role, wantedmembers)

                # Check whether the event is open.
                is_open = ('a' in wantedparticipantIDs)

                # Workflow:
                #  1. Get or create the EventRole.
                #  2. Remove unwanted invitations.
                #  3. Update the minimum and maximum number of participants.
                #  4. Adding wanted invitations

                try:  # check whether the EventRole already exists
                    # 1. Get the EventRole, stored in eventrole.
                    eventrole = EventRole.objects.get(event_id=event.id,
                                                      role_id=role.id)
                    print 'EventRole "{}" already exists.'.format(eventrole)
                except:
                    # Since there is no existing EventRole, we need to:
                    #  1. Create an EventRole, and save it as eventrole.
                    # and that's it! Adding participants is done below for both
                    # existing and recently created EventRoles.
                    try:
                        print 'event_id: {}'.format(event.id)
                        print 'role_id: {}'.format(role.id)
                        # TODO: Later feature...
                        #eventrole = EventRole(event_id=event.id,role_id=role.id,minimum=int(data['role'][role.id]['min']), maximum=int(data['role'][role.id]['max']))
                        eventrole = EventRole(event_id=event.id,
                                              role_id=role.id,
                                              is_open=is_open)
                        print 'No EventRole exists, creating {}.'.format(
                            eventrole)
                    except:
                        print 'Could not create eventrole.'
                        return HttpResponse(
                            json.dumps({
                                'type': 'error',
                                'message': 'Could not create eventrole.'
                            }))
                    try:
                        eventrole.clean_fields()
                        eventrole.save()
                        print 'eventrole saved: {}.'.format(eventrole)
                    except:
                        return HttpResponse(
                            json.dumps({
                                'type': 'error',
                                'message': 'Could not save eventrole.'
                            }))

                # 2. Remove unwanted invitations.
                currentpositions = eventrole.invited_positions.all()
                currentgroups = eventrole.invited_groups.all()
                currentmembers = eventrole.invited_members.all()
                print 'currentpositions: {}'.format(currentpositions)
                print 'currentgroups: {}'.format(currentgroups)
                print 'currentmembers: {}'.format(currentmembers)
                print 'EventRole already has these invitations:'
                for position in currentpositions:
                    print '>>{} ({})'.format(position, position.id)
                    if position not in wantedpositions:
                        print '-- ID is {}: We don\'t want {}.'.format(
                            group.id, group)
                        try:
                            #print 'DEBUG: {}'.format(eventrole.invited_positions)
                            pi = PositionInvitation.objects.get(
                                event_role=eventrole, position=position)
                            pi.delete()
                        except:
                            print 'Could not remove position {} from {}'.format(
                                group, currentgroups)
                            return HttpResponse(
                                json.dumps({
                                    'type':
                                    'error',
                                    'message':
                                    'Could not remove position ' +
                                    str(position) + ' from ' +
                                    currentpositions + '.'
                                }))
                    else:
                        print '++ ID is {}: We keep position {}.'.format(
                            position.id, position)
                for group in currentgroups:
                    print '>>{} ({})'.format(group, group.id)
                    if group not in wantedgroups:
                        print '-- ID is {}: We don\'t want {}.'.format(
                            group.id, group)
                        try:
                            #print 'DEBUG: {}'.format(eventrole.invited_groups)
                            gi = GroupInvitation.objects.get(
                                event_role=eventrole, group=group)
                            gi.delete()
                        except:
                            print 'Could not remove group {} from {}'.format(
                                group, currentgroups)
                            return HttpResponse(
                                json.dumps({
                                    'type':
                                    'error',
                                    'message':
                                    'Could not remove group ' + str(group) +
                                    ' from ' + currentgroups + '.'
                                }))
                    else:
                        print '++ ID is {}: We keep group {}.'.format(
                            group.id, group)
                for member in currentmembers:
                    print '>>{} ({})'.format(member, member.id)
                    if member not in wantedmembers:
                        print '-- ID is {}: We don\'t want {}.'.format(
                            member.id, member)
                        try:
                            #print 'DEBUG: {}'.format(eventrole.invited_members)
                            mi = MemberInvitation.objects.get(
                                event_role=eventrole, member=member)
                            mi.delete()
                        except:
                            print 'Could not remove member {} from {}'.format(
                                member, currentmembers)
                            return HttpResponse(
                                json.dumps({
                                    'type':
                                    'error',
                                    'message':
                                    'Could not remove member ' + str(member) +
                                    ' from ' + currentmembers + '.'
                                }))
                    else:
                        print '++ ID is {}: We keep member {}.'.format(
                            member.id, member)

                # Finally set whether the EventRole is open to all members:
                eventrole.is_open = is_open
                try:
                    eventrole.clean_fields()
                    eventrole.save()
                    print 'eventrole saved: {}.'.format(eventrole)
                except:
                    return HttpResponse(
                        json.dumps({
                            'type':
                            'error',
                            'message':
                            'Could not update whether the EventRole is open numbers.'
                        }))

                # 3. Update the minimum and maximum number of participants.
                # TODO: Later feature...
                #if eventrole.minimum != int(data['role'][role.id]['min']) or eventrole.maximum != int(data['role'][role.id]['max']):
                #	eventrole.minimum = int(data['role'][role.id]['min'])
                #	eventrole.maximum = int(data['role'][role.id]['max'])
                #	try:
                #		eventrole.clean_fields()
                #		eventrole.save()
                #		print 'eventrole saved: {}.'.format(eventrole)
                #	except:
                #		return HttpResponse(json.dumps({ 'type': 'error', 'message': 'Could not update eventrole max/min numbers.' }))

                # 4. Adding wanted invitations
                # Now that we have the eventrole and it has been stripped of its
                # unwanted participatns, let's add the wanted ones.
                # Workflow:
                # For each wanted participant,
                #   if they're not currently invited,
                #     create a {Position,Group,Member}Invitation and attach it to the EventRole

                # For each participant
                print 'Adding invitations:'
                print 'Wanted positions: {}'.format(wantedpositions)
                print 'Wanted groups: {}'.format(wantedgroups)
                print 'Wanted members: {}'.format(wantedmembers)
                for position in wantedpositions:
                    print '>>{} ({})'.format(position, position.id)
                    if position not in currentpositions:
                        print '++ Position {} is not invited: Create PositionInvitation!'.format(
                            position)
                        print eventrole
                        print position
                        pi = PositionInvitation(event_role=eventrole,
                                                position=position)
                        print '++ PositionInvitation created: '.format(pi)
                        try:
                            pi.clean_fields()
                            pi.save()
                            print '++ PositionInvitation saved'
                        except:
                            print 'ERROR: Could not save PositionInvitation {}'.format(
                                pi)
                            return HttpResponse(
                                json.dumps({
                                    'type':
                                    'error',
                                    'message':
                                    'Could not save PositionInvitation ' + pi +
                                    '.'
                                }))
                    else:
                        print '.. Position {} already invited: nothing to do. :-)'.format(
                            position)
                print 'Positions done!'
                for group in wantedgroups:
                    print '>>{} ({})'.format(group, group.id)
                    if group not in currentgroups:
                        print '++ Group {} is not invited: Create GroupInvitation!'.format(
                            group)
                        gi = GroupInvitation(event_role=eventrole, group=group)
                        print '++ GroupInvitation created: '.format(gi)
                        try:
                            gi.clean_fields()
                            gi.save()
                            print '++ GroupInvitation saved'
                        except:
                            print 'ERROR: Could not save GroupInvitation {}'.format(
                                gi)
                            return HttpResponse(
                                json.dumps({
                                    'type':
                                    'error',
                                    'message':
                                    'Could not save GroupInvitation ' + gi +
                                    '.'
                                }))
                    else:
                        print '.. Group {} already invited: nothing to do. :-)'.format(
                            group)
                print 'Groups done!'
                for member in wantedmembers:
                    print '>>{} ({})'.format(member, member.id)
                    if member not in currentmembers:
                        print '++ Member {} is not invited: Create MemberInvitation!'.format(
                            member)
                        mi = MemberInvitation(event_role=eventrole,
                                              member=member)
                        print '++ MemberInvitation created: '.format(mi)
                        try:
                            mi.clean_fields()
                            mi.save()
                            print '++ MemberInvitation saved'
                        except:
                            print 'ERROR: Could not save MemberInvitation {}'.format(
                                mi)
                            return HttpResponse(
                                json.dumps({
                                    'type':
                                    'error',
                                    'message':
                                    'Could not save MemberInvitation ' + mi +
                                    '.'
                                }))
                    else:
                        print '.. Member {} already invited: nothing to do. :-)'.format(
                            member)
                print 'All done!'
            else:  #if we don't want the role:
                print 'No role wanted.'
                try:  # check if the role exists and must be removed
                    eventrole = EventRole.objects.get(event__id=event.id,
                                                      role__id=role.id)
                    print 'Removing eventrole: %s' % eventrole
                    eventrole.delete()
                except:  # No role wanted. No role exists. All good.
                    print 'No role exists. All good.'
            print ' ..... '

        # for current tags:
        #	if tag not in submitted data:
        #		delete eventtag(event=event,tag=tag)
        # for all TagTypes:
        #	for submitted tags:
        #		if tag not currently saved:
        #			create eventtag(event=event,tag=tag)
        print 'Do tags.'
        print TagType.objects.all()

        print 'Iterate over eventtags'
        for tag in event.tags.all():
            try:
                print 'trying'
                tagslist = data['tag_type'][tagtype.id]
                #if tagslist == None:
                #	tagslist=[]
                #else:
                #	tagslist='hi'
                print 'tried'
            except:
                print 'excepting'
                tagslist = []
                print 'excepted'
            print 'tagslist: ' + str(tagslist)
            if str(tag.id) not in tagslist:
                print 'tag id ' + str(tag.id) + ' is not in ' + str(
                    data['tag_type'][tag.tag_type.id])
                print 'delete eventtag(event=event,tag=' + str(tag) + ')'
                try:
                    et = EventTag.objects.get(event=event, tag=tag)
                except:
                    print 'Could not get EventTag.'
                    return HttpResponse(
                        json.dumps({
                            'type': 'error',
                            'message': 'Could not get EventTag.'
                        }))
                try:
                    et.delete()
                except:
                    print 'Could not delete EventTag.'
                    return HttpResponse(
                        json.dumps({
                            'type':
                            'error',
                            'message':
                            'Could not delete EventTag ' + et + '.'
                        }))
            else:
                print 'tag id ' + str(tag.id) + ' is in ' + str(
                    data['tag_type'][tag.tag_type.id])
                print 'Do nothing...'
        print 'Iterate over tagtypes'
        for tagtype in TagType.objects.all():
            if event.event_type in tagtype.event_type.all():
                print tagtype
                print tagtype.id
                try:
                    print 'I am trying'
                    tagslist = data['tag_type'][tagtype.id]
                    print tagslist
                    if tagslist == None:
                        tagslist = []
                    print 'I tried'
                except:
                    print 'I am excepting'
                    tagslist = []
                    print 'I have excepted'
                print 'tagslist: ' + str(tagslist)
                for tag_id in tagslist:
                    tag = Tag.objects.get(pk=tag_id)
                    print tag
                    if tag not in event.tags.all():
                        print 'tag ' + str(tag) + ' is not in ' + str(
                            event.tags.all())
                        print 'create eventtag(event=event,tag=' + str(
                            tag) + ')'
                        try:
                            et = EventTag(event=event, tag=tag)
                        except:
                            print 'Could not create EventTag.'
                            return HttpResponse(
                                json.dumps({
                                    'type':
                                    'error',
                                    'message':
                                    'Could not create EventTag.'
                                }))
                        try:
                            et.clean_fields()
                            et.save()
                        except:
                            print 'Could not save EventTag.'
                            return HttpResponse(
                                json.dumps({
                                    'type':
                                    'error',
                                    'message':
                                    'Could not save EventTag ' + et + '.'
                                }))
                    else:
                        print 'tag ' + str(tag) + ' is already in ' + str(
                            event.tags.all())
                        print 'Nothing to do...'
            else:
                print 'tagtype ' + str(
                    tagtype) + ' is not valid for this event'

        return HttpResponse(
            json.dumps({
                'type': 'success',
                'event_id': event.id
            }))
Ejemplo n.º 4
0
def save_event(request):
    if request.is_ajax() or True:
        print 'Is AJAX'
        # TODO: Add handler for these below. They are required and must be submitted or else the form will not validate. Or perhaps the clean_fields() exception is enough...?
        import pprint
        print 'Hér kemur hrátt data:'
        pprint.pprint(request.POST['data'])
        print 'Hér kemur JSON útgáfan:'
        data = json.loads(request.POST['data'])
        pprint.pprint(data)
        t = data['title']
        d = data['description']
        dtb = timezone.make_aware(parser.parse(data['date_time_begin']),
                                  timezone.get_default_timezone())
        dte = timezone.make_aware(parser.parse(data['date_time_end']),
                                  timezone.get_default_timezone())
        et_id = data['event_type']
        try:
            event_id = data['event_id']
            if event_id == '':
                # If no event id has been supplied, we'll create a new event.
                event = Event(title=t,
                              description=d,
                              date_time_begin=dtb,
                              date_time_end=dte,
                              event_type_id=et_id)
            else:
                # else we update the existing one.
                event = Event.objects.get(pk=event_id)
                event.title = t
                event.description = d
                event.date_time_begin = dtb
                event.date_time_end = dte
                event.event_type_id = et_id
                #return HttpResponse('Event fields updated.')
            # Now save the event
            try:
                event.clean_fields()
                event.save()
                print 'The event is: ------'
                print(vars(event))
                print '--------------------'
            except:
                return HttpResponse("Hello, world. Could not save event.")

            # Now that the event has been taken care of, let's sort out the event roles etc.
            # Flow:
            # For each role:
            for role in Role.objects.all():
                print 'Role ID %s' % role.id
                print 'Role is %s' % role
                try:  #if we want the role:
                    currentparticipants = [
                    ]  # This will be populated below if the event exists (and currently has any participants).
                    currentgroups = [
                    ]  # This will be populated below if the event exists (and currently has any participants).
                    currentmembers = [
                    ]  # This will be populated below if the event exists (and currently has any participants).

                    wantedparticipantIDs = data['role'][
                        role.id]['participants']
                    print 'Wanted participantsID: {}'.format(
                        wantedparticipantIDs)
                    wantedgroups = [
                        Group.objects.get(pk=int(groupid[1:]))
                        for groupid in wantedparticipantIDs
                        if groupid[0] == 'g'
                    ]
                    print 'We want event role {} with groups {}'.format(
                        role, wantedgroups)
                    wantedmembers = [
                        Member.objects.get(pk=int(memberid[1:]))
                        for memberid in wantedparticipantIDs
                        if memberid[0] == 'm'
                    ]
                    print 'We want event role {} with members {}'.format(
                        role, wantedmembers)
                    try:  #check whether the EventRole already exists
                        # In the event that an EventRole already exists, we have to:
                        #  1. Get the EventRole, stored in eventrole.
                        #  2. Remove unwanted participants
                        # Adding wanted participants is shared with EventRoles that
                        # need to be created so we're doing that later on.
                        #  3. Update the minimum and maximum number of participants

                        # 1.
                        eventrole = EventRole.objects.get(event_id=event.id,
                                                          role_id=role.id)
                        print 'EventRole "{}" already exists.'.format(
                            eventrole)

                        # 2.
                        #currentgroups= GroupInvitation.objects.filter(event_role=eventrole)
                        currentgroups = eventrole.invited_groups.all()
                        currentmembers = eventrole.invited_members.all()
                        print 'currentgroups: {}'.format(currentgroups)
                        print 'currentmembers: {}'.format(currentmembers)
                        print 'EventRole already has these invitations:'
                        for group in currentgroups:
                            print '>>{} ({})'.format(group, group.id)
                            #print 'Comare {} with {}'.format(group.id,wantedgroups)
                            if group not in wantedgroups:
                                print '-- ID is {}: We don\'t want {}.'.format(
                                    group.id, group)
                                #gi = GroupInvitation(event_role=eventrole,group=group)
                                #print 'Removing group {} from eventrole {}'.format(group,eventrole)
                                #print 'DEBUG'
                                try:
                                    print 'DEBUG: {}'.format(
                                        eventrole.invited_groups)
                                    gi = GroupInvitation.objects.get(
                                        event_role=eventrole, group=group)
                                    #print gi
                                    gi.delete()
                                    print 'BINGO'
                                except:
                                    print 'Could not remove group {} from {}'.format(
                                        group, currentgroups)
                            else:
                                print '++ ID is {}: We keep {}.'.format(
                                    group.id, group)
                        for member in currentmembers:
                            print '>>{} ({})'.format(member, member.id)
                            if member not in wantedmembers:
                                print '-- ID is {}: We don\'t want {}.'.format(
                                    member.id, member)
                                try:
                                    print 'DEBUG: {}'.format(
                                        eventrole.invited_members)
                                    mi = MemberInvitation.objects.get(
                                        event_role=eventrole, member=member)
                                    #print mi
                                    mi.delete()
                                    print 'BINGO'
                                except:
                                    print 'Could not remove member {} from {}'.format(
                                        member, currentmembers)
                            else:
                                print '++ ID is {}: We keep {}.'.format(
                                    member.id, member)
                        # 3.
                        if eventrole.minimum != int(data['role'][
                                role.id]['min']) or eventrole.maximum != int(
                                    data['role'][role.id]['max']):
                            eventrole.minimum = int(
                                data['role'][role.id]['min'])
                            eventrole.maximum = int(
                                data['role'][role.id]['max'])
                            try:
                                eventrole.clean_fields()
                                eventrole.save()
                                print 'eventrole saved: {}.'.format(eventrole)
                            except:
                                return HttpResponse(
                                    'Hello, world. Could not update eventrole max/min numbers.'
                                )
                    except:  #else
                        # Since there is no existing EventRole, we need to:
                        #  1. Create an EventRole, and save it as eventrole.
                        # and that's it! Adding participants is done below for both
                        # existing and recently created EventRoles.
                        eventrole = EventRole(
                            event_id=event.id,
                            role_id=role.id,
                            minimum=int(data['role'][role.id]['min']),
                            maximum=int(data['role'][role.id]['max']))
                        print 'No EventRole exists, creating {}.'.format(
                            eventrole)
                        try:
                            eventrole.clean_fields()
                            eventrole.save()
                            print 'eventrole saved: {}.'.format(eventrole)
                        except:
                            return HttpResponse(
                                'Hello, world. Could not save eventrole.')

                    # Now that we have the eventrole and it has been stripped of its
                    # unwanted participatns, let's add the wanted ones.
                    # Workflow:
                    # For each wanted participant,
                    #   if they're not currently invited,
                    #     create a GroupInvitation and attach it to the EventRole

                    # For each participant
                    print 'Adding invitations:'
                    print 'Wanted groups: {}'.format(wantedgroups)
                    print 'Wanted members: {}'.format(wantedmembers)
                    for group in wantedgroups:
                        print '>>{} ({})'.format(group, group.id)
                        if group not in currentgroups:
                            print '++ Group {} is not invited: Create GroupInvitation!'.format(
                                group)
                            gi = GroupInvitation(event_role=eventrole,
                                                 group=group)
                            print '++ GroupInvitation created: '.format(gi)
                            try:
                                gi.clean_fields()
                                gi.save()
                                print '++ GroupInvitation saved'
                            except:
                                print 'ERROR: Could not save GroupInvitation {}'.format(
                                    gi)
                        else:
                            print '.. Group {} already invited: nothing to do. :-)'.format(
                                group)
                    print 'Groups done!'
                    for member in wantedmembers:
                        print '>>{} ({})'.format(member, member.id)
                        if member not in currentmembers:
                            print '++ Member {} is not invited: Create MemberInvitation!'.format(
                                member)
                            mi = MemberInvitation(event_role=eventrole,
                                                  member=member)
                            print '++ MemberInvitation created: '.format(mi)
                            try:
                                mi.clean_fields()
                                mi.save()
                                print '++ MemberInvitation saved'
                            except:
                                print 'ERROR: Could not save MemberInvitation {}'.format(
                                    mi)
                        else:
                            print '.. Member {} already invited: nothing to do. :-)'.format(
                                member)
                    print 'All done!'
                except:  #if we don't want the role:
                    print 'No role wanted.'
                    try:  # check if the role exists and must be removed
                        eventrole = EventRole.objects.get(event__id=event.id,
                                                          role__id=role.id)
                        print 'Removing eventrole: %s' % eventrole
                        eventrole.delete()
                    except:  # No role wanted. No role exists. All good.
                        print 'No role exists. All good.'
                print ' ..... '
        except:
            return HttpResponse("Hello, world. Could not create event.")
        return HttpResponse(event.id)
    else:
        return HttpResponse("Hello, world. Not AJAX request.")