Beispiel #1
0
def edit_mpa(request, pk):
    mpa = get_object_or_404(Mpa, pk=pk)
    if (request.POST):
        # Got a form submission
        editform = MpaForm(request.POST, instance=mpa)
        if editform.is_valid():
            mpasaved = editform.save()
            try:
                reversion.set_comment(editform.cleaned_data.get("edit_comment"))
            except:
                pass
            try:
                reversion.set_user(request.user)
            except:
                pass
            try:
                reversion.add_meta(VersionMetadata, comment=editform.cleaned_data.get("edit_comment"), reference=editform.cleaned_data.get("edit_reference"))
            except:
                pass
            return HttpResponseRedirect(reverse('mpa-siteinfo', kwargs={'pk': pk}))
    else:
        editform = MpaForm(instance=mpa)
    return render_to_response('mpa/Mpa_editform.html', {
        'form': editform,
        'mpa': mpa,
        'respond_url': reverse('mpa-editsite', kwargs={'pk': pk}),
    }, context_instance=RequestContext(request))
    def obj_create(self, bundle, **kwargs):
        '''
        created objects should automatically have a status of Human Created
        '''
        status_update = StatusUpdate.objects.get(status_en='Human Created')
        username = bundle.request.GET['username']
        user = User.objects.filter(username=username)[0]
        status_id = status_update.id

        if can_assign_users(user) is False and 'assigned_user' in bundle.data:
            del(bundle.data['assigned_user'])

        comment_uri = self.create_comment(
            bundle.data['comment'],
            status_id,
            user
        )
        bundle.data['actor_comments'] = [
            comment_uri
        ]
        with reversion.create_revision():
            bundle = super(ActorResource, self)\
                .obj_create(bundle, **kwargs)
            reversion.add_meta(
                VersionStatus,
                status='created',
                user=user
            )
            reversion.set_user(user)
            reversion.set_comment(bundle.data['comment'])
        update_object.delay(username)
        return bundle
Beispiel #3
0
def make_profile(backend, user, response, is_new=False, *args, **kwargs):
    if is_new:
        if not hasattr(user, "profile"):
            profile = Profile(user=user)
            profile.language = Language.get_python2()
            if backend.name == "google-oauth2":
                profile.name = response["displayName"]
            elif backend.name in ("github", "facebook") and "name" in response:
                profile.name = response["name"]
            else:
                logger.info("Info from %s: %s", backend.name, response)
            profile.save()
            form = ProfileForm(instance=profile, user=user)
        else:
            data = backend.strategy.request_data()
            logger.info(data)
            form = ProfileForm(data, instance=user.profile, user=user)
            if form.is_valid():
                with transaction.atomic(), revisions.create_revision():
                    form.save()
                    revisions.set_user(user)
                    revisions.set_comment("Updated on registration")
                    return
        return render(
            backend.strategy.request,
            "registration/profile_creation.jade",
            {"title": "Create your profile", "form": form},
        )
def editInclusionOrder(request, dss_id, inc_type):
    if inc_type not in ['cluster', 'data_element']:
        raise Http404
    item = get_object_or_404(aristotle_dse.models.DataSetSpecification, pk=dss_id)
    if not user_can_edit(request.user, item):
        if request.user.is_anonymous():
            return redirect(reverse('friendly_login') + '?next=%s' % request.path)
        else:
            raise PermissionDenied

    item_type, field_name = {
        'cluster': (aristotle_dse.models.DSSClusterInclusion, 'child'),
        'data_element': (aristotle_dse.models.DSSDEInclusion, 'data_element'),
        }.get(inc_type)

    num_values = item_type.objects.filter(dss=item.id).count()
    if num_values > 0:
        extra = 0
    else:
        extra = 1

    ValuesFormSet = modelformset_factory(
        item_type,
        formset=HiddenOrderModelFormSet,
        can_order=True,
        fields=('id',),
        extra=extra
    )

    if request.method == 'POST':
        formset = ValuesFormSet(request.POST, request.FILES)
        if formset.is_valid():
            with transaction.atomic(), reversion.create_revision():
                item.save()  # do this to ensure we are saving reversion records for the DSS, not just the values
                formset.save(commit=False)
                for form in formset.forms:
                    if form['id'].value() not in [deleted_record['id'].value() for deleted_record in formset.deleted_forms]:
                        inc = item_type.objects.get(pk=form['id'].value())
                        if inc.dss != item:
                            raise PermissionDenied
                        inc.order = form['ORDER'].value()
                        # inc.maximum_occurances = form['maximum_occurances'].value()
                        # value = form.save(commit=False) #Don't immediately save, we need to attach the value domain
                        # value.dss = item
                        inc.save()
                for obj in formset.deleted_objects:
                    obj.delete()
                reversion.set_user(request.user)
                reversion.set_comment(construct_change_message(request, None, [formset, ]))

                return redirect(reverse("aristotle_mdr:item", args=[item.id]))
    else:
        formset = ValuesFormSet(
            queryset=item_type.objects.filter(dss=item.id),
        )
    return render(
        request,
        "aristotle_dse/actions/edit_inclusion_order.html",
        {'item': item, 'formset': formset, 'include_type': inc_type, 'value_model': item_type, }
    )
def update_entities(model_dict, model_objects, appendable_keys):
    '''
    model_dict is the key value store of updated elements
    model_objects are the models, these can be of type Actor, Bulletin or
    Incident
    delegates actual updating of fields to update_entity where the field
    is to be replaced and to update_entity_appendable where the field is
    to be added to
    '''
    appendable_dict, remainder_dict = separate_field_types(
        model_dict, appendable_keys)

    for model in model_objects:
        model_dict_copy = remainder_dict.copy()
        model_dict_copy = update_related_actors(model_dict_copy, model)
        model = update_entity_appendable(appendable_dict, model)
        model = update_entity_status(model_dict, model)
        model = update_entity(model_dict_copy, model)
        user = model_dict['user']
        with reversion.create_revision():
            model.save()
            reversion.add_meta(
                VersionStatus,
                status='edited',
                user=user
            )
            reversion.set_user(user)
            comment_text = model_dict['comment']
            reversion.set_comment(comment_text)
Beispiel #6
0
def change_mark(request, slug):
    if request.method == "POST":
        data = json.loads(request.body.decode("utf-8"))
        grade_system = data.get("grade_system")
        pk = data.get("pk")
        new_comment = data.get("comment")
        new_mark = data.get("mark")
        if grade_system is not None and pk is not None and new_mark is not None:
            with reversion.create_revision():
                mark, old_mark = MarkAPI.set_mark(grade_system, pk, new_mark)
                if mark.problem:
                    assignment_hierarchy = "{0:s}/{1:s}/{2:s}".format(
                        mark.problem.task.assignment.name, mark.problem.task.name, mark.problem.name
                    )
                elif mark.task:
                    assignment_hierarchy = "{0:s}/{1:s}".format(mark.task.assignment.name, mark.task.name)
                else:
                    assignment_hierarchy = "{0:s}".format(mark.assignment.name)
                reversion.set_user(request.user)
                reversion.set_comment(
                    """Mark for '{0:s}' student, for '{1:s}'
                    assignment was changed from '{2:d}' to '{3:d}' by '{4:s}' user """.format(
                        mark.student.username, assignment_hierarchy, old_mark, mark.mark, request.user.username
                    )
                )
        if grade_system is not None and pk is not None and new_comment is not None:
            MarkAPI.set_comment(grade_system, pk, new_comment)
    return HttpResponse()
Beispiel #7
0
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            raise Exception("Not logged in!  Only staff have access to this function")

        if not request.user.is_staff and not request.user.is_superuser:
            raise Exception("Only staff have access to this function")

        keys = [('location', Location), ('time_block', TimeBlock), ('time_slot', TimeSlot)]
        key_text = 0
        key_db_object = 1

        game_id = request.POST.get('id')
        game = Game.objects.get(id=game_id)

        changed = []

        for key in keys:
            incoming_id = request.POST.get(key[key_text])
            old = getattr(game, key[key_text])
            new = key[key_db_object].objects.get(id=incoming_id) if incoming_id else None

            setattr(game, key[key_text], new)
            if old != new:
                changed.append(key[key_text])

        changed.sort()
        game.last_scheduled = timezone.now()

        with reversion.create_revision():
            reversion.set_user(request.user)
            reversion.set_comment("AJAX Schedule Submission - %s Changed" % ", ".join(changed))

            game.save()
Beispiel #8
0
 def post(self, request, *args, **kwargs):
     if "room" in request.POST:
         if request.POST["room"] != "" and request.POST["room"] != 0:
             roomid = request.POST["room"][0]
             room = get_object_or_404(Room, pk=roomid)
         else:
             room = None
     else:
         room = None
     response = super(DeviceApiLend, self).post(request)
     if request.POST["device"] != "" and response.status_code == 201:
         device = Device.objects.get(pk=request.POST["device"])
         device.currentlending = self.object
         if room:
             device.room = room
             reversion.set_user(request.user)
             reversion.set_comment("Device marked as lend")
             try:
                 template = MailTemplate.objects.get(usage="room")
             except:
                 template = None
             if not template == None:
                 recipients = []
                 for recipient in template.default_recipients.all():
                     recipient = recipient.content_object
                     if isinstance(recipient, Group):
                         recipients += recipient.lageruser_set.all().values_list("email")[0]
                     else:
                         recipients.append(recipient.email)
                 template.send(self.request, recipients, {"device": device, "user": self.request.user})
         reversion.set_ignore_duplicates(True)
         device.save()
     return response
Beispiel #9
0
    def create(self, validated_data):
        request = self.context['request']
        venue_id = validated_data['venue']
        slots = validated_data['slots']
        talk = validated_data.get('talk')
        page = validated_data.get('page')

        try:
            existing_schedule_item = ScheduleItem.objects.get(
                venue_id=venue_id, slots__in=slots)
        except ScheduleItem.DoesNotExist:
            revisions.set_user(request.user)
            revisions.set_comment("Created using Schedule Editor")
        else:
            existing_schedule_item.talk = talk
            existing_schedule_item.page = page
            existing_schedule_item.slots = slots
            # Clear any existing details that aren't editable by the
            # schedule edit view
            existing_schedule_item.details = ''
            existing_schedule_item.notes = ''
            existing_schedule_item.css_class = ''
            existing_schedule_item.expand = False
            existing_schedule_item.save()
            revisions.set_user(request.user)
            revisions.set_comment("Updated using Schedule Editor")
            return existing_schedule_item
        return super(ScheduleItemSerializer, self).create(validated_data)
Beispiel #10
0
 def get(self, request, attendance_id):
     a = get_object_or_404(Attendance,  pk=attendance_id)
     with transaction.atomic(), reversion.create_revision():
         a.rotate()
         reversion.set_user(request.user)
         reversion.set_comment("Rotating by %s" % request.user)
     return HttpResponseRedirect(reverse('training:course', args=[a.clazz.course.id]))
Beispiel #11
0
 def set_denied(self, actor):
     if not self.can_deny(actor):
         raise PermissionDenied
     with DoAction() as action, reversion.create_revision():
         self.state = STATE_DENIED
         self.save()
         revisions.set_user(actor)
         action.set(actor=actor, verb='denied trip request', target=self, state=STATE_DENIED, style='trip-denied')
Beispiel #12
0
 def set_completed(self, actor):
     if not self.can_complete(actor):
         raise PermissionDenied
     with DoAction() as action, reversion.create_revision():
         self.state = STATE_COMPLETED
         self.save()
         revisions.set_user(actor)
         action.set(actor=actor, verb='completed trip', target=self, state=STATE_CLOSED, style='trip-completed')
Beispiel #13
0
 def set_open(self, actor):
     if not self.can_open(actor):
         raise PermissionDenied
     with DoAction() as action, reversion.create_revision():
         self.state = STATE_OPEN
         self.save()
         revisions.set_user(actor)
         action.set(actor=actor, verb='opened trip', target=self, state=STATE_OPEN, style='trip-opened')
Beispiel #14
0
 def set_cancelled(self, actor):
     if not self.can_cancel(actor):
         raise PermissionDenied
     with DoAction() as action, reversion.create_revision():
         self.state = STATE_CANCELLED
         self.save()
         revisions.set_user(actor)
         action.set(actor=actor, verb='cancelled trip', target=self, state=STATE_CANCELLED, style='trip-cancelled')
Beispiel #15
0
 def get(self, request, course_id, clazz_id, attendance_status):
     c1 = get_object_or_404(Course, pk=course_id)
     c2 = get_object_or_404(Class,  pk=clazz_id)
     with transaction.atomic(), reversion.create_revision():
         Attendance.attendance_all_set_status(c1, c2, attendance_status)
         reversion.set_user(request.user)
         reversion.set_comment("Setting to %s by %s" % (attendance_status, request.user))
     return HttpResponseRedirect(reverse('training:course', args=[course_id]))
    def done(self, form_list, **kwargs):
        reversion.set_user(self.request.user)
        reversion.set_comment("Added via concept wizard")
        item = None

        for form in form_list:
            item = form.save()
        return HttpResponseRedirect(url_slugify_concept(item))
Beispiel #17
0
	def setUp(self):
		self.user = mommy.make(UserProfile, is_superuser=True)

		document = mommy.prepare(InformationDocument, text="text")
		with transaction.atomic(), revisions.create_revision():
				document.save()
				revisions.set_user(self.user)
				revisions.set_comment('test version')
Beispiel #18
0
 def save(self, **kwargs):
     if kwargs.pop('no_revision', False):
         super(RevisionedMixin, self).save(**kwargs)
     else:
         with revisions.create_revision():
             revisions.set_user(kwargs.pop('version_user', None))
             revisions.set_comment(kwargs.pop('version_comment', ''))
             super(RevisionedMixin, self).save(**kwargs)
 def create_revision(self, bundle, user, status_update):
     with reversion.create_revision():
         reversion.set_user(user)
         reversion.set_comment(bundle.data['comment'])
         reversion.add_meta(
             VersionStatus,
             status=status_update,
             user=user
         )
Beispiel #20
0
 def wrapped(self, request, *args, **kwargs):
     with reversion.create_revision():
         ret = fn(self, request, *args, **kwargs)
         reversion.set_user(request.user)
         reversion.add_meta(RevisionProject, project=request.project)
         if getattr(self, 'log_obj', None):
             reversion.add_meta(RevisionLogActivity,
                                log_activity=self.log_obj)
     return ret
Beispiel #21
0
	def setUp(self):
		self.user = mommy.make(UserProfile, is_superuser=True)

		self.document = mommy.prepare(InformationDocument)
		with transaction.atomic(), revisions.create_revision():
			self.document.save()
			revisions.set_user(self.user)
			revisions.set_comment('test version')
		self.document.set_all_permissions(mommy.make(Group))
Beispiel #22
0
def handle_edit(request, document, formset=None, initial=None):
	if request.method == 'POST':
		creation = document.is_in_creation
		form = document.Form(request.POST, instance=document, initial=initial, user=request.user, creation=creation)
		if form.is_valid() and (formset is None or formset.is_valid()):
			cleaned_data = form.cleaned_data

			document.url_title = cleaned_data['url_title']

			# save the document and also save the user and the comment the user added
			with transaction.atomic(), revisions.create_revision():
				document.handle_edit(cleaned_data)
				document.save()
				document.save_formset(formset)
				revisions.set_user(request.user)
				revisions.set_comment(cleaned_data['comment'])

			if not document.has_perms() or creation:
				document.set_all_permissions(cleaned_data['group'])

			# delete Autosave
			try:
				autosave = TemporaryDocumentText.objects.get(document=document)
				autosave.delete()
			except TemporaryDocumentText.DoesNotExist:
				pass

			return True, form
	else:
		# load Autosave
		autosave = None
		try:
			autosave = TemporaryDocumentText.objects.get(document=document)
			autosaved = True
		except TemporaryDocumentText.DoesNotExist:
			autosaved = False

		if 'restore' in request.GET:
			autosaved = False

		if 'restore' in request.GET and autosave is not None:
			form_data = {
				'text': autosave.text,
				'url_title': document.url_title,
			}
			if initial is None:
				initial = {}
			initial.update(form_data)

		form = document.Form(initial=initial, instance=document, user=request.user, creation=document.is_in_creation)

		form.autosave = autosaved
		if autosaved:
			form.autosave_date = autosave.created

	return False, form
Beispiel #23
0
    def obj_update(self, bundle, **kwargs):
        username = bundle.request.GET['username']
        user = User.objects.filter(username=username)[0]
        bundle.data['id'] = kwargs['pk']

        if self.can_edit(user, bundle, Actor) is False:
            raise ImmediateHttpResponse(
                HttpForbidden('You do not have permission to edit this entity')
            )

        if self.is_finalized(
            Actor,
            kwargs['pk'],
            'most_recent_status_actor'
        ) and can_finalize(user) is False:
            raise ImmediateHttpResponse(
                HttpForbidden('This item has been finalized')
            )

        if can_assign_users(user) is False and 'assigned_user' in bundle.data:
            del(bundle.data['assigned_user'])

        status_id = self.id_from_url(bundle.data)
        status_update = StatusUpdate.filter_by_perm_objects.get_update_status(
            user,
            status_id
        )
        comment_uri = self.create_comment(
            bundle.data['comment'],
            status_update.id,
            user
        )
        if "condition" not in bundle.data:
            bundle.data['condition'] = None
        if "POB" not in bundle.data:
            bundle.data['POB'] = None
        if "current_location" not in bundle.data:
            bundle.data['current_location'] = None
        try:
            bundle.data['actor_comments'].append(comment_uri)
        except KeyError:
            bundle.data['actor_comments'] = [comment_uri, ]

        with reversion.create_revision():
            bundle = super(ActorResource, self)\
                .obj_update(bundle, **kwargs)
            reversion.add_meta(
                VersionStatus,
                status='edited',
                user=user
            )
            reversion.set_user(user)
            reversion.set_comment(bundle.data['comment'])
        update_object.delay(username)
        return bundle
Beispiel #24
0
def revert(request):
	if not request.is_ajax() or not request.POST:
		raise Http404

	version_id = request.POST['id']
	document_url_title = request.POST['url_title']
	document = get_object_or_404(Document, url_title=document_url_title)
	check_permissions(document, request.user, [document.edit_permission_name])
	versions = revisions.get_for_object(document)

	if not document.can_be_reverted:
		raise SuspiciousOperation('This Document can not be reverted!')

	# find the we want to revert to
	revert_version = None
	for version in versions:
		if version.pk == int(version_id):
			revert_version = version
			break

	if revert_version is None:
		# user supplied version_id that does not exist
		raise SuspiciousOperation('Could not find document')

	revert_version.revision.revert(delete=False)
	fields = revert_version.field_dict
	document_class = ContentType.objects.get_for_id(fields.pop('polymorphic_ctype')).model_class()

	# Remove all references to parent objects, rename ForeignKeyFields, extract ManyToManyFields.
	new_fields = fields.copy()
	many_to_many_fields = {}
	for key in fields.keys():
		if "_ptr" in key:
			del new_fields[key]
			continue
		if hasattr(document_class, key):
			field = getattr(document_class, key).field
			if isinstance(field, models.ManyToManyField):
				many_to_many_fields[key] = fields[key]
			else:
				new_fields[field.attname] = fields[key]
			del new_fields[key]

	reverted_document = document_class(**new_fields)
	with transaction.atomic(), revisions.create_revision():
		reverted_document.save()
		# Restore ManyToManyFields
		for key in many_to_many_fields.keys():
			getattr(reverted_document, key).clear()
			getattr(reverted_document, key).add(*many_to_many_fields[key])
		revisions.set_user(request.user)
		revisions.set_comment(
			_('reverted to revision \"{revision_comment}\"'.format(revision_comment=revert_version.revision.comment)))

	return HttpResponse(reverse('versions', args=[reverted_document.url_title]))
Beispiel #25
0
	def setUpTestData(cls):
		cls.user = mommy.make(UserProfile, is_superuser=True)
		cls.document = mommy.prepare(InformationDocument)
		with transaction.atomic(), revisions.create_revision():
			cls.document.save()
			revisions.set_user(cls.user)
			revisions.set_comment('test version')
		cls.group = mommy.make(Group)
		cls.user.groups.add(cls.group)
		cls.document.set_all_permissions(mommy.make(Group))
		assign_perm("information_pages.add_informationdocument", cls.group)
Beispiel #26
0
    def form_valid(self, form):
        # since the form doesn't have the user or time, we need to insert it
        form.instance.user = self.request.user
        form.instance.last_modified = timezone.now()

        with reversion.create_revision():
            reversion.set_user(self.request.user)
            reversion.set_comment("Form Submission - New")

            result = super(NewGameView, self).form_valid(form)
        self.send_email()
        return result
Beispiel #27
0
 def mark_as_used(self, user=None, comment='', subscription=None):
     if not self.used:
         with transaction.atomic(), reversion.create_revision():
             self.used = True
             self.subscription = subscription  # which subscription was paid
             self.save()
             if user is not None and not user.is_anonymous():
                 reversion.set_user(user)
             reversion.set_comment('Marked as used. ' + comment)
         return True
     else:
         return False
Beispiel #28
0
 def post(self, request, pk, *args, **kwargs):
     reversion.set_user(request.user)
     if self.commission.locked:
         self.response = redirect('Coms:Detail:Done', pk=pk)
     form = DetailForm(request.POST, instance=self.commission)
     contactformset = self.contactfactory(request.POST)
     if contactformset.is_valid() and form.is_valid():
         form.instance.contacts = contactformset.save()
         form.instance.submitted = True
         detail = form.save()
         self.response = redirect("{0}#{1}".format(reverse('Coms:commissions'), detail.id))
     self.context.update({'form': form, 'contactformset': contactformset})
    def obj_update(self, bundle, **kwargs):
        username = bundle.request.GET['username']
        user = User.objects.filter(username=username)[0]

        if self.can_edit(user, bundle, Bulletin) is False:
            raise ImmediateHttpResponse(
                HttpForbidden('You do not have permission to edit this entity')
            )

        # permission checks
        if self.is_finalized(
            Bulletin,
            kwargs['pk'],
            'most_recent_status_bulletin'
        ) and can_finalize(user) is False:
            raise ImmediateHttpResponse(
                HttpForbidden('This item has been finalized')
            )

        if can_assign_users(user) is False and 'assigned_user' in bundle.data:
            del(bundle.data['assigned_user'])

        # decide on available status
        status_id = self.id_from_url(bundle.data)

        status_update = StatusUpdate.filter_by_perm_objects.get_update_status(
            user,
            status_id
        )

        # create the commnt from the status update and the bundled comment
        comment_uri = self.create_comment(
            bundle.data['comment'],
            status_update.id,
            user
        )
        try:
            bundle.data['bulletin_comments'].append(comment_uri)
        except KeyError:
            bundle.data['bulletin_comments'] = [comment_uri, ]

        with reversion.create_revision():
            bundle = super(BulletinResource, self)\
                .obj_update(bundle, **kwargs)
            reversion.add_meta(
                VersionStatus,
                status='edited',
                user=user
            )
            reversion.set_user(user)
            reversion.set_comment(bundle.data['comment'])
        update_object.delay(username)
        return bundle
Beispiel #30
0
    def perform_update(self, serializer):
        """
        Update an existing `Measurement` instance, given the validated data.

        Doesn't hit DB if nothing changed(Doesn't create redundant revisions).
        """
        if not (self.get_object().headers == serializer.validated_data.get('headers') and
                self.get_object().table_data == serializer.validated_data.get('table_data')):
            with reversion.create_revision():
                serializer.save()
                reversion.set_user(self.request.user)
                self.save_recent_activity(RecentActivity.UPDATE, obj=self.get_object().unit, unit=self.get_object().unit.pk,
                                          experiment=[unicode(obj.pk) for obj in self.get_object().unit.experiments.all()])
Beispiel #31
0
    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        page = self.get_comment_page()

        if self.is_comment_locked():
            return HttpResponseForbidden()

        parent = request.POST.get('parent')
        if parent:
            try:
                parent = int(parent)
            except ValueError:
                return HttpResponseNotFound()
            else:
                if not Comment.objects.filter(
                        hidden=False, id=parent, page=page).exists():
                    return HttpResponseNotFound()

        form = CommentForm(request, request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.profile
            comment.page = page

            with LockModel(write=(Comment, Revision, Version),
                           read=(ContentType, )), revisions.create_revision():
                revisions.set_user(request.user)
                revisions.set_comment(_('Posted comment'))
                comment.save()

            # add notification for reply
            if comment.parent and comment.parent.author != comment.author:
                notification_rep = Notification(owner=comment.parent.author,
                                                comment=comment,
                                                category='Reply')
                notification_rep.save()

            add_mention_notifications(comment)

            return HttpResponseRedirect(request.path)

        context = self.get_context_data(object=self.object, comment_form=form)
        return self.render_to_response(context)
    def obj_update(self, bundle, **kwargs):
        username = bundle.request.GET['username']
        user = User.objects.filter(username=username)[0]

        if self.can_edit(user, bundle, Bulletin) is False:
            raise ImmediateHttpResponse(
                HttpForbidden(
                    'You do not have permission to edit this entity'))

        # permission checks
        if self.is_finalized(
                Bulletin, kwargs['pk'],
                'most_recent_status_bulletin') and can_finalize(user) is False:
            raise ImmediateHttpResponse(
                HttpForbidden('This item has been finalized'))

        if can_assign_users(user) is False and 'assigned_user' in bundle.data:
            del (bundle.data['assigned_user'])

        # decide on available status
        status_id = self.id_from_url(bundle.data)

        status_update = StatusUpdate.filter_by_perm_objects.get_update_status(
            user, status_id)

        # create the commnt from the status update and the bundled comment
        comment_uri = self.create_comment(bundle.data['comment'],
                                          status_update.id, user)
        try:
            bundle.data['bulletin_comments'].append(comment_uri)
        except KeyError:
            bundle.data['bulletin_comments'] = [
                comment_uri,
            ]

        with reversion.create_revision():
            bundle = super(BulletinResource, self)\
                .obj_update(bundle, **kwargs)
            reversion.add_meta(VersionStatus, status='edited', user=user)
            reversion.set_user(user)
            reversion.set_comment(bundle.data['comment'])
        update_object.delay(username)
        return bundle
Beispiel #33
0
 def post(self, request, *args, **kwargs):
     if "room" in request.POST:
         if request.POST["room"] != "" and request.POST["room"] != 0:
             roomid = request.POST["room"][0]
             room = get_object_or_404(Room, pk=roomid)
         else:
             room = None
     else:
         room = None
     response = super(DeviceApiLend, self).post(request)
     if request.POST["device"] != "" and response.status_code == 201:
         device = Device.objects.get(pk=request.POST["device"])
         device.currentlending = self.object
         if room:
             device.room = room
             reversion.set_user(request.user)
             reversion.set_comment("Device marked as lend")
             try:
                 template = MailTemplate.objects.get(
                     usage="room",
                     department=self.request.user.main_department)
             except:
                 template = None
                 messages.error(
                     self.request,
                     _('MAIL NOT SENT - Template for room change does not exist for your main department'
                       ))
             if template is not None:
                 recipients = []
                 for recipient in template.default_recipients.all():
                     recipient = recipient.content_object
                     if isinstance(recipient, Group):
                         recipients += recipient.lageruser_set.all(
                         ).values_list("email")[0]
                     else:
                         recipients.append(recipient.email)
                 template.send(self.request, recipients, {
                     "device": device,
                     "user": self.request.user
                 })
         reversion.set_ignore_duplicates(True)
         device.save()
     return response
Beispiel #34
0
	def test_last_author(self):
		# test whether last author is part of page
		response = self.app.get(self.document.get_view_url(), user=self.user)
		self.assertIn('<i>by</i> {}'.format(self.user.username), response.body.decode('utf-8'))

		# create a second user
		user2 = mommy.make(UserProfile, is_superuser=True)
		user2.groups.add(self.group)

		# create second revision
		self.document.text_en = 'christi was here'
		with transaction.atomic(), revisions.create_revision():
			self.document.save()
			revisions.set_user(user2)
			revisions.set_comment('test version 2')

		# test whether last author is part of page
		response = self.app.get(self.document.get_view_url(), user=self.user)
		self.assertIn('<i>by</i> {}'.format(user2.username), response.body.decode('utf-8'))
Beispiel #35
0
def edit_profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=request.profile)
        if form.is_valid():
            with transaction.atomic(), revisions.create_revision():
                form.save()
                revisions.set_user(request.user)
                revisions.set_comment(_('Updated on site'))

            return HttpResponseRedirect(request.path)
    else:
        form = ProfileForm(instance=request.profile)

    return render(
        request, 'user/edit-profile.html', {
            'form': form,
            'title': _('Edit profile'),
            'has_math_config': bool(settings.MATHOID_URL),
        })
Beispiel #36
0
def game_edit(request, *args, **kwargs):
    game = get_object_or_404(models.Game, pk=kwargs.get('game_pk'))
    if request.method == 'POST':
        with revisions.create_revision():
            form = forms.GameForm(request.POST, instance=game)
            if form.is_valid():
                form.save()
                revisions.set_user(request.user)
                return HttpResponseRedirect(
                    reverse('core:game_detail', args=[game.id]))
            else:
                context = {'form': form, 'game': game}
                return render(request,
                              'core/game_form_edit.html',
                              context=context)
    else:
        form = forms.GameForm(instance=game)
        context = {'form': form, 'game': game}
    return render(request, 'core/game_form_edit.html', context=context)
Beispiel #37
0
    def form_valid(self, form):
        # save as a revision
        self.work.updated_by_user = self.request.user

        with reversion.create_revision():
            reversion.set_user(self.request.user)
            resp = super(EditWorkView, self).form_valid(form)

        # ensure any docs for this work at initial pub date move with it, if it changes
        if 'publication_date' in form.changed_data:
            old_date = form.initial[
                'publication_date'] or self.work.commencement_date

            if old_date and self.work.publication_date:
                for doc in Document.objects.filter(work=self.work,
                                                   expression_date=old_date):
                    doc.expression_date = self.work.publication_date
                    doc.save()

        # if the work title changes, ensure matching document titles do too
        if 'title' in form.changed_data:
            old_title = form.initial['title']
            if old_title:
                for doc in Document.objects.filter(work=self.work,
                                                   title=old_title):
                    doc.title = self.work.title
                    doc.save()

        if form.has_changed():
            # signals
            work_changed.send(sender=self.__class__,
                              work=self.work,
                              request=self.request)
            messages.success(self.request, "Work updated.")

            # rename publication-document if frbr_uri has changed
            if 'frbr_uri' in form.changed_data:
                try:
                    self.work.publication_document.save()
                except PublicationDocument.DoesNotExist:
                    pass

        return resp
Beispiel #38
0
    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        page = self.get_comment_page()

        with LockModel(write=(Comment, Revision, Version),
                       read=(Profile, ContentType, Submission, Problem)):
            form = CommentForm(request, request.POST)
            if form.is_valid():
                comment = form.save(commit=False)
                comment.author = request.user.profile
                comment.page = page
                with revisions.create_revision():
                    revisions.set_user(request.user)
                    revisions.set_comment(_('Posted comment'))
                    comment.save()
                return HttpResponseRedirect(request.path)

        context = self.get_context_data(object=self.object, comment_form=form)
        return self.render_to_response(context)
Beispiel #39
0
    def restore(self, request, *args, **kwargs):
        # check permissions on the OLD object
        if not DocumentPermissions().has_object_permission(request, self, self.document):
            self.permission_denied(self.request)

        revision = self.get_object()

        # check permissions on the NEW object
        version = revision.version_set.all()[0]
        document = version.object_version.object
        if not DocumentPermissions().has_object_permission(request, self, document):
            self.permission_denied(self.request)

        with reversion.create_revision():
            reversion.set_user(request.user)
            reversion.set_comment("Restored revision %s" % revision.id)
            revision.revert()

        return Response(status=200)
Beispiel #40
0
    def post(self, request, frbr_uri, version_id):
        version = self.work.versions().filter(pk=version_id).first()
        if not version:
            raise Http404()

        with reversion.create_revision():
            reversion.set_user(request.user)
            reversion.set_comment("Restored version %s" % version.id)
            version.revert()
        messages.success(request, 'Restored version %s' % version.id)

        # signals
        work_changed.send(sender=self.work.__class__,
                          work=self.work,
                          request=request)

        url = request.GET.get('next') or reverse(
            'work', kwargs={'frbr_uri': self.work.frbr_uri})
        return redirect(url)
Beispiel #41
0
    def post(self, request, *args, **kwargs):
        if "lending" not in request.DATA:
            return Response({"error": "you need to provide a valid lending id"}, status=status.HTTP_400_BAD_REQUEST)
        if "room" in request.DATA:
            if request.DATA["room"] != "" and request.DATA["room"] != 0:
                roomid = request.DATA["room"]
                room = get_object_or_404(Room, pk=roomid)
            else:
                room = None
        else:
            room = None

        lending = get_object_or_404(Lending, pk=request.DATA["lending"])
        if lending.device and lending.device != "":
            device = lending.device
            device.currentlending = None
            if room:
                device.room = room
                reversion.set_user(request.user)
                try:
                    template = MailTemplate.objects.get(usage="room")
                except:
                    template = None
                    messages.error(self.request, _('MAIL NOT SENT - Template for room change does not exist'))
                if template is not None:
                    recipients = []
                    for recipient in template.default_recipients.all():
                        recipient = recipient.content_object
                        if isinstance(recipient, Group):
                            recipients += recipient.lageruser_set.all().values_list("email")[0]
                        else:
                            recipients.append(recipient.email)
                    template.send(self.request, recipients, {"device": device, "user": self.request.user})
                reversion.set_comment(_("Device returned and moved to room {0}").format(device.room))
            device.save()
        else:
            pass

        lending.returndate = datetime.datetime.now()
        lending.save()

        return Response({"success": "device is returned"}, status=status.HTTP_200_OK)
Beispiel #42
0
    def put(self, request, pk, **kwargs):
        response = super(DeviceApiRoomChange, self).put(request, pk)
        try:
            template = MailTemplate.objects.get(usage="room")
        except:
            template = None
            messages.error(self.request, _('MAIL NOT SENT - Template for room change does not exist'))
        if template is not None:
            recipients = []
            for recipient in template.default_recipients.all():
                recipient = recipient.content_object
                if isinstance(recipient, Group):
                    recipients += recipient.lageruser_set.all().values_list("email")[0]
                else:
                    recipients.append(recipient.email)
            template.send(self.request, recipients, {"device": self.get_object(), "user": self.request.user})

        reversion.set_user(request.user)
        reversion.set_comment(_("Device moved to room {0}").format(self.get_object().room))
        return response
Beispiel #43
0
    def obj_create(self, bundle, **kwargs):
        username = bundle.request.GET['username']
        user = User.objects.filter(username=username)[0]
        status_update = StatusUpdate.objects.get(status_en='Human Created')

        if can_assign_users(user) is False and 'assigned_user' in bundle.data:
            del (bundle.data['assigned_user'])

        comment_uri = self.create_comment(bundle.data['comment'],
                                          status_update.id, user)
        bundle.data['incident_comments'] = [comment_uri]

        with reversion.create_revision():
            bundle = super(IncidentResource, self)\
                .obj_create(bundle, **kwargs)
            reversion.add_meta(VersionStatus, status='created', user=user)
            reversion.set_user(user)
            reversion.set_comment(bundle.data['comment'])
        update_object.delay(username)
        return bundle
Beispiel #44
0
def make_profile(backend, user, response, is_new=False, *args, **kwargs):
    if is_new:
        if not hasattr(user, 'profile'):
            profile = Profile(user=user)
            profile.language = Language.get_python2()
            logger.info('Info from %s: %s', backend.name, response)
            profile.save()
            return
#            form = ProfileForm(instance=profile, user=user)
        else:
            data = backend.strategy.request_data()
            logger.info(data)
            return
            form = ProfileForm(data, instance=user.profile, user=user)
            if form.is_valid():
                with transaction.atomic(), revisions.create_revision():
                    form.save()
                    revisions.set_user(user)
                    revisions.set_comment('Updated on registration')
                    return
Beispiel #45
0
    def delete(self, request, app, model):
        if request.data:
            dict_mapp = request.data
            model = apps.get_model(app, model)
            objs = model.objects.filter(**dict_mapp)
            with transaction.atomic(), reversion.create_revision():
                [objs[i].save() for i in range(len(objs))]
                reversion.set_user(request.user)
                reversion.set_comment(request.method)
                reversion.set_date_created(
                    date_created=datetime.datetime.now())
            GenericSzl = getGenericSerializer(model)
            serializer = GenericSzl(objs, many=True)
            org = serializer.data
            objs.delete()
            audit_log_list(org, request, app, model)
            return Response({'Received data': request.data})

        else:
            return Response({"return none instead": "return none instead"})
Beispiel #46
0
    def done(self, form_list, **kwargs):
        reversion.set_user(self.request.user)
        reversion.set_comment("Added via data element concept wizard")

        oc = self.get_object_class()
        pr = self.get_property()
        dec = None
        for form in form_list:
            saved_item = form.save()
            if type(saved_item) == MDR.Property:
                pr = saved_item
                messages.success(
                    self.request,
                    mark_safe(_("New Property '{name}' Saved - <a href='{url}'>id:{id}</a>").format(
                        url=url_slugify_concept(saved_item),
                        name=saved_item.name, id=saved_item.id
                    ))
                )
            if type(saved_item) == MDR.ObjectClass:
                oc = saved_item
                messages.success(
                    self.request,
                    mark_safe(_("New Object Class '{name}' Saved - <a href='{url}'>id:{id}</a>").format(
                        url=url_slugify_concept(saved_item),
                        name=saved_item.name, id=saved_item.id
                    ))
                )
            if type(saved_item) == MDR.DataElementConcept:
                dec = saved_item
                messages.success(
                    self.request,
                    mark_safe(_("New Data Element Concept '{name}' Saved - <a href='{url}'>id:{id}</a>").format(
                        url=url_slugify_concept(saved_item),
                        name=saved_item.name, id=saved_item.id
                    ))
                )
        if dec is not None:
            dec.objectClass = oc
            dec.property = pr
            dec.save()
        return HttpResponseRedirect(url_slugify_concept(dec))
Beispiel #47
0
    def setUpTestData(cls):
        cls.profile = models.Profile.objects.create(username="******",
                                                    email="*****@*****.**",
                                                    is_superuser=True,
                                                    is_active=True,
                                                    is_staff=True)

        cls.vatrate = models.VatRate.objects.create(start_at='2014-03-05',
                                                    rate=0.20,
                                                    comment='test1')

        cls.events = {}

        with reversion.create_revision():
            reversion.set_user(cls.profile)
            cls.events[1] = models.Event.objects.create(
                name="TE E1", start_date=date.today())

        with reversion.create_revision():
            reversion.set_user(cls.profile)
            cls.events[2] = models.Event.objects.create(
                name="TE E2", start_date='2014-03-05')

        with reversion.create_revision():
            reversion.set_user(cls.profile)
            cls.events[1].description = "A test description"
            cls.events[1].save()
Beispiel #48
0
    def create(self, request, *args, **kwargs):

        data = request.data
        if 'concept_type' in request.data.keys():
            # We've been passed a single object
            manifest = {'metadata': [data]}
        else:
            manifest = data

        try:
            created = []
            errors = []
            with transaction.atomic():
                for s in Deserializer(manifest):

                    if s.object.workgroup is None or perms.user_can_submit_to_workgroup(
                            request.user, s.object.workgroup):
                        with reversion.create_revision():
                            created.append({
                                'uuid': s.object.uuid,
                                'url': s.object.get_absolute_url()
                            })
                            s.submitter = request.user
                            s.object.recache_states()

                            reversion.set_user(request.user)
                            reversion.set_comment(_("Imported using API"))
                            s.save()
                    else:
                        errors.append({
                            'message':
                            'You don\'t have permission to create an item in the {} Workgroup'
                            .format(s.object.workgroup)
                        })

            return Response({'created': created, 'errors': errors})
        except Exception as e:
            if settings.DEBUG and 'explode' in request.query_params.keys():
                raise
            return Response({'error': str(e)})
Beispiel #49
0
	def test_show_author_to(self):
		author_str = '<i>by</i> {}'.format(self.user.username)

		self.document.show_author_to = InformationDocument.SHOW_AUTHOR_TO_EVERYONE
		with transaction.atomic(), revisions.create_revision():
			self.document.save()
			revisions.set_user(self.user)
			revisions.set_comment('test version 2')
		self.assertIn(author_str, self.app.get(self.document.get_view_url(), user=self.user).body.decode('utf-8'))
		self.app.reset()
		self.assertIn(author_str, self.app.get(self.document.get_view_url()).body.decode('utf-8'))

		self.document.show_author_to = InformationDocument.SHOW_AUTHOR_TO_LOGGED_IN_USERS
		with transaction.atomic(), revisions.create_revision():
			self.document.save()
			revisions.set_user(self.user)
			revisions.set_comment('test version 3')
		self.assertIn(author_str, self.app.get(self.document.get_view_url(), user=self.user).body.decode('utf-8'))
		self.app.reset()
		self.assertNotIn(author_str, self.app.get(self.document.get_view_url()).body.decode('utf-8'))

		self.document.show_author_to = InformationDocument.SHOW_AUTHOR_TO_NO_ONE
		with transaction.atomic(), revisions.create_revision():
			self.document.save()
			revisions.set_user(self.user)
			revisions.set_comment('test version 4')
		self.assertNotIn(author_str, self.app.get(self.document.get_view_url(), user=self.user).body.decode('utf-8'))
		self.app.reset()
		self.assertNotIn(author_str, self.app.get(self.document.get_view_url()).body.decode('utf-8'))
Beispiel #50
0
def edit_profile(request):
    profile = Profile.objects.get(user=request.user)
    if profile.mute:
        raise Http404()
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=profile, user=request.user)
        if form.is_valid():
            with transaction.atomic(), revisions.create_revision():
                form.save()
                revisions.set_user(request.user)
                revisions.set_comment(_('Updated on site'))

            if newsletter_id is not None:
                try:
                    subscription = Subscription.objects.get(user=request.user, newsletter_id=newsletter_id)
                except Subscription.DoesNotExist:
                    if form.cleaned_data['newsletter']:
                        Subscription(user=request.user, newsletter_id=newsletter_id, subscribed=True).save()
                else:
                    if subscription.subscribed != form.cleaned_data['newsletter']:
                        subscription.update(('unsubscribe', 'subscribe')[form.cleaned_data['newsletter']])

            return HttpResponseRedirect(request.path)
    else:
        form = ProfileForm(instance=profile, user=request.user)
        if newsletter_id is not None:
            try:
                subscription = Subscription.objects.get(user=request.user, newsletter_id=newsletter_id)
            except Subscription.DoesNotExist:
                form.fields['newsletter'].initial = False
            else:
                form.fields['newsletter'].initial = subscription.subscribed

    tzmap = getattr(settings, 'TIMEZONE_MAP', None)
    return render(request, 'user/edit_profile.jade', {
        'form': form, 'title': _('Edit profile'),
        'TIMEZONE_MAP': tzmap or 'http://momentjs.com/static/img/world.png',
        'TIMEZONE_BG': getattr(settings, 'TIMEZONE_BG', None if tzmap else '#4E7CAD'),
    })
Beispiel #51
0
def make_profile(backend, user, response, is_new=False, *args, **kwargs):
    if is_new:
        if not hasattr(user, 'profile'):
            profile = Profile(user=user)
            profile.language = Language.get_python2()
            profile.save()
            form = ProfileForm(instance=profile, user=user)
        else:
            data = backend.strategy.request_data()
            logger.info(data)
            form = ProfileForm(data, instance=user.profile, user=user)
            if form.is_valid():
                with transaction.atomic(), revisions.create_revision():
                    form.save()
                    revisions.set_user(user)
                    revisions.set_comment('Updated on registration')
                    return
        return render(backend.strategy.request,
                      'registration/profile_creation.html', {
                          'title': 'Create your profile',
                          'form': form
                      })
Beispiel #52
0
    def setupPeople(self):
        names = ["Regulus Black", "Sirius Black", "Lavender Brown", "Cho Chang", "Vincent Crabbe", "Vincent Crabbe", "Bartemius Crouch", "Fleur Delacour", "Cedric Diggory", "Alberforth Dumbledore", "Albus Dumbledore", "Dudley Dursley", "Petunia Dursley", "Vernon Dursley", "Argus Filch", "Seamus Finnigan", "Nicolas Flamel", "Cornelius Fudge", "Goyle", "Gregory Goyle", "Hermione Granger", "Rubeus Hagrid", "Igor Karkaroff", "Viktor Krum", "Bellatrix Lestrange", "Alice Longbottom", "Frank Longbottom", "Neville Longbottom", "Luna Lovegood", "Xenophilius Lovegood",  # noqa
                 "Remus Lupin", "Draco Malfoy", "Lucius Malfoy", "Narcissa Malfoy", "Olympe Maxime", "Minerva McGonagall", "Mad-Eye Moody", "Peter Pettigrew", "Harry Potter", "James Potter", "Lily Potter", "Quirinus Quirrell", "Tom Riddle", "Mary Riddle", "Lord Voldemort", "Rita Skeeter", "Severus Snape", "Nymphadora Tonks", "Dolores Janes Umbridge", "Arthur Weasley", "Bill Weasley", "Charlie Weasley", "Fred Weasley", "George Weasley", "Ginny Weasley", "Molly Weasley", "Percy Weasley", "Ron Weasley", "Dobby", "Fluffy", "Hedwig", "Moaning Myrtle", "Aragog", "Grawp"]  # noqa
        for i, name in enumerate(names):
            with reversion.create_revision():
                reversion.set_user(random.choice(self.profiles))

                newPerson = models.Person.objects.create(name=name)
                if i % 3 == 0:
                    newPerson.email = "*****@*****.**"

                if i % 5 == 0:
                    newPerson.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"

                if i % 7 == 0:
                    newPerson.address = "1 Person Test Street \n Demoton \n United States of TEC \n RMRF 567"

                if i % 9 == 0:
                    newPerson.phone = "01234 567894"

                newPerson.save()
                self.people.append(newPerson)
Beispiel #53
0
def activate_profile(request):
    profile = Profile.objects.get(user=request.user)
    if profile.mute:
        raise Http404()
    if request.method == 'POST':
        form = ProfileActivateForm(request.POST,
                                   instance=profile,
                                   user=request.user)
        if form.is_valid():
            with transaction.atomic(), revisions.create_revision():
                form.save()
                revisions.set_user(request.user)
                revisions.set_comment(_('Updated on site'))

            return HttpResponseRedirect(reverse('user_page'))
    else:
        form = ProfileActivateForm(instance=profile, user=request.user)

    return render(request, 'user/activate-profile.html', {
        'form': form,
        'title': _('Congratulations!')
    })
Beispiel #54
0
    def handle(self, *args, **options):
        path = options['path'][0]

        list_multiple = []
        list_doesnt_exist = []
        with open(path, 'r') as csvfile:
            spamreader = csv.reader(csvfile, delimiter='	')
            list_wrong_date = []

            for row in spamreader:
                regex_result = url_pattern.match(row[2])
                article_year = int(regex_result.group("year"))
                article_month = int(regex_result.group("month"))
                article_slug = regex_result.group("slug")
                article_title = row[1]

                date_result = date_pattern.match(row[0])
                date_year = int(date_result.group("year"))
                date_month = int(date_result.group("month"))
                date_day = date_result.group("day")

                if not (article_month == date_month
                        and article_year == date_year):
                    list_wrong_date.append(row[2] + " > " + row[0])
                else:
                    try:
                        article = Article.objects.get(
                            title=article_title,
                            publishin__month=article_month,
                            publishin__year=article_year)
                        article.text = row[3]
                        article.slug = article_slug
                        reversion.set_user(article.author)
                        article.save()
                    except Article.DoesNotExist:
                        pass
                    except Article.MultipleObjectsReturned:
                        pass
Beispiel #55
0
def commit_variant_edit(var_data, genevieve_effect_data, relation_id,
                        commit_comment, user):
    """
    Custom update method that records revisions and reports new version.
    """
    if commit_comment:
        reversion.set_comment(comment=commit_comment)
    reversion.set_user(user=user)
    tags = {
        'chrom_b37': var_data['chrom'],
        'pos_b37': var_data['pos'],
        'ref_allele_b37': var_data['ref_allele'],
        'var_allele_b37': var_data['var_allele'],
    }
    variant, _ = Variant.objects.get_or_create(tags=tags)

    if relation_id:
        relation = Relation.objects.get(id=relation_id)
        relation.tags = genevieve_effect_data
    else:
        relation = Relation(variant=variant, tags=genevieve_effect_data)
    relation.save()
    return relation
Beispiel #56
0
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            raise Exception(
                "Not logged in!  Only staff have access to this function")

        if not request.user.is_staff and not request.user.is_superuser:
            raise Exception("Only staff have access to this function")

        keys = [('location', Location), ('time_block', TimeBlock),
                ('time_slot', TimeSlot)]
        key_text = 0
        key_db_object = 1

        game_id = request.POST.get('id')
        game = Game.objects.get(id=game_id)

        changed = []

        for key in keys:
            incoming_id = request.POST.get(key[key_text])
            old = getattr(game, key[key_text])
            new = key[key_db_object].objects.get(
                id=incoming_id) if incoming_id else None

            setattr(game, key[key_text], new)
            if old != new:
                changed.append(key[key_text])

        changed.sort()
        game.last_scheduled = timezone.now()

        with reversion.create_revision():
            reversion.set_user(request.user)
            reversion.set_comment("AJAX Schedule Submission - %s Changed" %
                                  ", ".join(changed))

            game.save()
    def done(self, form_list, **kwargs):
        saved_item = None

        for form in form_list:
            saved_item = form.save(commit=False)
            if saved_item is not None:
                saved_item.submitter = self.request.user
                saved_item.save()

                with reversion.create_revision():
                    reversion.set_user(self.request.user)
                    reversion.set_comment("Added via concept wizard")

                    form.save_custom_fields(saved_item)
                    form.save_m2m()

                    if 'results_postdata' in self.request.session:
                        extra_formsets = self.get_extra_formsets(
                            item=self.model,
                            postdata=self.request.session['results_postdata'])
                        formsets_invalid = self.validate_formsets(
                            extra_formsets)
                        if not formsets_invalid:
                            final_formsets = []
                            for info in extra_formsets:
                                if info['saveargs'] is not None:
                                    info['saveargs']['item'] = saved_item
                                else:
                                    info['formset'].instance = saved_item
                                final_formsets.append(info)

                            self.save_formsets(final_formsets)
                        self.request.session.pop('results_postdata')

                    saved_item.save()

        return HttpResponseRedirect(url_slugify_concept(saved_item))
Beispiel #58
0
    def save(self):
        new_entry = not hasattr(self, "registration")
        if new_entry:
            self.registration = Registration(
                user=self.user,
                registration_date=timezone.now(),
                payment=PaymentOption.objects.all()[0])

        with transaction.atomic(), reversion.create_revision():
            reversion.set_user(self.user)
            reversion.set_comment("Form Submission - %s" %
                                  ("Initial" if new_entry else "Update"))

            self.registration.last_updated = timezone.now()
            self.registration.save()

            old_regs = {}
            for reg in BlockRegistration.objects.filter(
                    registration=self.registration):
                old_regs[reg.time_block] = reg

            for key, field in self.time_block_fields().iteritems():
                time_block = TimeBlock.objects.filter(
                    id=key.split("_")[1])[0].text
                if time_block in old_regs:
                    old_regs[time_block].attendance = field.initial
                    old_regs[time_block].save()
                    del old_regs[time_block]
                else:
                    BlockRegistration(registration=self.registration,
                                      time_block=time_block,
                                      attendance=field.initial).save()

            for obsolete in old_regs.values():
                obsolete.delete()

        self.send_mail(self.registration, new_entry)
Beispiel #59
0
    def test_text_field_types(self):
        with reversion.create_revision():
            reversion.set_user(self.profile)
            self.event.name = "New event name"  # Simple text
            self.event.description = "hello world"  # Long text
            self.event.save()

        # Find the most recent version
        currentVersion = versioning.RIGSVersion.objects.get_for_object(
            self.event).latest(field_name='revision__date_created')
        diff = currentVersion.changes

        # There are two changes
        self.assertEqual(len(diff.field_changes), 2)
        self.assertFalse(currentVersion.changes.items_changed)
        self.assertTrue(currentVersion.changes.fields_changed)
        self.assertTrue(currentVersion.changes.anything_changed)

        # Only one has "linebreaks"
        self.assertEqual(sum([x.linebreaks for x in diff.field_changes]), 1)

        # None are "long" (email address)
        self.assertEqual(sum([x.long for x in diff.field_changes]), 0)

        # Try changing email field in person
        with reversion.create_revision():
            reversion.set_user(self.profile)
            self.person.email = "*****@*****.**"
            self.person.save()

        # Find the most recent version
        currentVersion = versioning.RIGSVersion.objects.get_for_object(
            self.person).latest(field_name='revision__date_created')
        diff = currentVersion.changes

        # Should be declared as long
        self.assertTrue(diff.field_changes[0].long)
Beispiel #60
0
    def form_valid(self, form):
        existing = self.get_object()
        with revisions.create_revision():
            response = super(TalkReview, self).form_valid(form)
            revisions.set_user(self.request.user)
            if existing:
                revisions.set_comment("Review Modified")
            else:
                revisions.set_comment("Review Created")

        # Because Review.save() was called before any scores were added,
        # the str() on the version would have had the previous total. Update.
        review = self.get_object()
        version = Version.objects.get_for_object(review).order_by(
            '-pk').first()
        version.object_repr = str(review)
        version.save()

        talk = review.talk
        if talk.status == SUBMITTED:
            talk.status = UNDER_CONSIDERATION
            talk.save()

        return response