예제 #1
0
def log_cr_upd(sender, **kwargs):
    if not (issubclass(sender, LogEntry) or issubclass(sender, Session)):
        instance = kwargs["instance"]
        if not isinstance(instance, Session):
            created = kwargs["created"]
            try:
                usr = User.objects.all()[0]
                try:
                    rpr = instance.__unicode__()
                except:
                    rpr = repr(instance)
                content_type = ContentType.objects.get(
                    app_label=instance._meta.app_label, model=instance._meta.module_name
                )
                if created:
                    action_flag = ADDITION
                else:
                    action_flag = CHANGE
                    log_entry = LogEntry(
                        object_id=instance.id,
                        object_repr=rpr,
                        action_flag=action_flag,
                        content_type=content_type,
                        user=usr,
                    )
                    log_entry.save()
            except:
                pass
예제 #2
0
def after_delete(*args, **kwargs):
    instance = kwargs['instance']
    if isinstance(instance, Session): return
    log_entry = construct_log_entry(**kwargs)
    log_entry['action_flag'] = DELETION
    entry = LogEntry(**log_entry)
    entry.save()
예제 #3
0
파일: models.py 프로젝트: dedkovd/record
def after_delete(*args, **kwargs):
    instance = kwargs['instance']
    if isinstance(instance, Session): return
    log_entry = construct_log_entry(**kwargs)
    log_entry['action_flag'] = DELETION
    entry = LogEntry(**log_entry)
    entry.save() 
예제 #4
0
파일: utils.py 프로젝트: ernop/tracker
def make_le(request, obj, change_message, action_flag=2):
    from django.contrib.admin.models import LogEntry
    from day.models import User
    '''make logentry.'''
    try:
        if request is None:
            user = User.objects.filter(username='******')[0]
            ip=''
            if not obj:
                class Bag():
                    pass
                obj=Bag()
                obj.id=None
            if obj.__class__ == user.__class__:
                user = obj
            #just user ernie
            content_type=None
        else:
            user = request.user
            ip = request.META['REMOTE_ADDR']
            content_type = get_contenttype(obj.__class__)
        if user.is_anonymous():
            log.info('anon user did an action, saving as ernie.')
            user = User.objects.get(username='******')
        object_id = obj.id
        object_repr = str(obj)
        le = LogEntry(user=user, content_type=content_type, object_id=object_id, object_repr=object_repr, action_flag=action_flag, change_message=change_message)
        le.save()
    except Exception, e:
        log.error(e)
        ipdb()
예제 #5
0
    def items(self):
        log_list = LogEntry.objects.filter(
            content_type__app_label='dnd').order_by('-action_time').all()[:50]

        result = []

        for entry in log_list:
            if False:
                entry = LogEntry()

            change_message = entry.change_message
            url = None
            object_rep = entry.object_repr
            try:
                obj = entry.get_edited_object()
                object_rep = obj.__unicode__()
                url = obj.get_absolute_url()
            except Exception:
                pass

            result.append({
                'object_rep': object_rep,
                'change_message': change_message,
                'url': url,
                'is_addition': entry.is_addition(),
                'is_change': entry.is_change(),
                'is_deletion': entry.is_deletion(),
                'author': entry.user,
                'pub_date': entry.action_time
            })

        return result
예제 #6
0
def batch_update_view(model_admin, request, queryset, field_names=None, exclude_field_names=None):

        # removes fields not included in field_names
    def remove_fields(form, field_names):
        for field in list(form.base_fields.keys()):
            if not field in field_names:
                del form.base_fields[field]
        return form

        # the return value is the form class, not the form class instance
    f = model_admin.get_form(request)
    # If no field names are given, do them all
    if field_names is None:
        field_names = f.base_fields.keys()
    if exclude_field_names is not None:
        # should do this with list comprehension
        temp_names = []
        for n in field_names:
            if n not in exclude_field_names:
                temp_names.append(n)
        field_names = temp_names
    form_class = remove_fields(f, field_names)
    if request.method == 'POST':
        form = form_class()

        # for this there is a hidden field 'form-post' in the html template the edit is confirmed
        if 'form-post' in request.POST:
            form = form_class(request.POST)
            if form.is_valid():
                for item in queryset.all():
                    changed_list = []
                    for field_name in field_names:
                        if request.POST.get('{}_use'.format(field_name,)) == 'on':
                            setattr(item, field_name, form.cleaned_data[field_name])
                            changed_list.append(field_name)
                    if len(changed_list) > 0:
                        l = LogEntry(
                                    user=request.user,
                                    content_type=ContentType.objects.get_for_model(model_admin.model, for_concrete_model=False),
                                    object_id=item.pk,
                                    object_repr=unicode(item),
                                    action_flag=CHANGE,
                                    change_message = 'Changed {}'.format(', '.join(changed_list),),
                                    )
                        l.save()
                    item.save()
                model_admin.message_user(request, "Bulk updated {} records".format(queryset.count()))
                return HttpResponseRedirect(request.get_full_path())

        return render(
            request,
            'admin/batch_editing_intermediary.html',
            context={
                'form': form,
                'items': queryset,
                'fieldnames': field_names,
                'media': model_admin.media,
            }
        )
예제 #7
0
def test_document_merge_with_log_entries(document, join):
    # create some log entries
    document_contenttype = ContentType.objects.get_for_model(Document)
    # creation
    creation_date = timezone.make_aware(datetime(1991, 5, 1))
    creator = User.objects.get_or_create(username="******")[0]
    LogEntry.objects.bulk_create([
        LogEntry(
            user_id=creator.id,
            content_type_id=document_contenttype.pk,
            object_id=document.id,
            object_repr=str(document),
            change_message="first input",
            action_flag=ADDITION,
            action_time=creation_date,
        ),
        LogEntry(
            user_id=creator.id,
            content_type_id=document_contenttype.pk,
            object_id=join.id,
            object_repr=str(join),
            change_message="first input",
            action_flag=ADDITION,
            action_time=creation_date,
        ),
        LogEntry(
            user_id=creator.id,
            content_type_id=document_contenttype.pk,
            object_id=join.id,
            object_repr=str(join),
            change_message="major revision",
            action_flag=CHANGE,
            action_time=timezone.now(),
        ),
    ])

    # document has two log entries from fixture
    assert document.log_entries.count() == 3
    assert join.log_entries.count() == 2
    join_pk = join.pk
    document.merge_with([join], "combine log entries", creator)
    # should have 5 log entries after the merge:
    # original 2 from fixture, 1 of the two duplicates, 1 unique,
    # and 1 documenting the merge
    assert document.log_entries.count() == 5
    # based on default sorting, most recent log entry will be first
    # - should document the merge event
    merge_log = document.log_entries.first()
    # log action with specified user
    assert creator.id == merge_log.user_id
    assert "combine log entries" in merge_log.change_message
    assert merge_log.action_flag == CHANGE
    # not flagged for review when merged by a user
    assert "SCRIPTMERGE" not in document.needs_review

    # reassociated log entry should include old pgpid
    moved_log = document.log_entries.all()[1]
    assert " [PGPID %s]" % join_pk in moved_log.change_message
예제 #8
0
 def render(self, context):
     if self.user is None:
         context[self.varname] = LogEntry.all().order('-action_time')[:int(self.limit)]
     else:
         user_id = self.user
         if not user_id.isdigit():
             user_id = db.Key(context[self.user].id)
         context[self.varname] = LogEntry.all().filter('user ='******'-action_time')[:int(self.limit)]
     return ''
예제 #9
0
def patch_admin() -> None:
    TenantModel = get_tenant_model()

    def get_tenant_field(model: type) -> Optional[Field]:
        for field in model._meta.fields:  # type: ignore
            if getattr(field, 'related_model', None) == TenantModel:
                return field
        return None

    class AutoTenantMixin:
        model: Model

        def get_fields(self,
                       request: HttpRequest,
                       obj: Model = None) -> Sequence[Field]:
            fields = super(AutoTenantMixin,
                           self).get_fields(request, obj=obj)  # type: ignore
            tenant_field = get_tenant_field(self.model)
            if tenant_field and tenant_field.name in fields:
                fields.remove(tenant_field.name)
            return fields

    admin.ModelAdmin.__bases__ = (
        AutoTenantMixin, ) + admin.ModelAdmin.__bases__

    def save_model(self, request: HttpRequest, obj: Model, form: Form,
                   change: bool) -> None:
        if not change:
            tenant_field = get_tenant_field(obj)
            if tenant_field:
                setattr(obj, tenant_field.attname,
                        request.session['active_tenant'])
        obj.save()

    admin.ModelAdmin.save_model = save_model

    if not getattr(LogEntry, 'tenant_id', None):
        # Adding this value is delegated to a postgres trigger - that way it will always
        # be set, without us having to query the database. We still need it as a field,
        # because it's tricky to .annotate() in the place where it's used. Otherwise,
        # we could write a cleaner version that just used default - however we can't do
        # that here because Django will send an explicit NULL, but we would want it not
        # to send it at all.
        LogEntry.add_to_class(
            'tenant_id',
            models.IntegerField(blank=True, null=True),
        )

    get_admin_url = admin.models.LogEntry.get_admin_url

    def get_admin_url_with_tenant(self):
        url = get_admin_url(self)
        if self.tenant_id and url:
            return '{0}?__tenant={1}'.format(url, self.tenant_id)
        return url

    admin.models.LogEntry.get_admin_url = get_admin_url_with_tenant
예제 #10
0
파일: models.py 프로젝트: dedkovd/record
def after_save(*args, **kwargs):
    instance = kwargs['instance']
    if isinstance(instance, LogEntry): return
    if isinstance(instance, Session): return
    log_entry = construct_log_entry(**kwargs)
    if log_entry['object_id'] == -1: return
    created = kwargs['created']
    log_entry['action_flag'] = ADDITION if created else CHANGE
    entry = LogEntry(**log_entry)
    entry.save()
예제 #11
0
def after_save(*args, **kwargs):
    instance = kwargs['instance']
    if isinstance(instance, LogEntry): return
    if isinstance(instance, Session): return
    log_entry = construct_log_entry(**kwargs)
    if log_entry['object_id'] == -1: return
    created = kwargs['created']
    log_entry['action_flag'] = ADDITION if created else CHANGE
    entry = LogEntry(**log_entry)
    entry.save()
예제 #12
0
    def wrapper(*args, **kwargs):
        log_entry = {}
        request = args[0]
        if not request.user.is_authenticated():
            return fn(*args, **kwargs)

        log_entry['user'] = request.user
        log_entry['object_repr'] = fn.__name__
        log_entry['action_flag'] = 5
        entry = LogEntry(**log_entry)
        entry.save()
        return fn(*args, **kwargs)
예제 #13
0
 def _create_log_entry(self, action):
     if not threadlocals.get_current_user() or threadlocals.get_current_user().is_anonymous():
         user = User.objects.get(username="******")
     else:
         user = threadlocals.get_current_user()
     history = LogEntry(
         user=user, object_id=self.pk, action_flag=action, content_type=ContentType.objects.get_for_model(self)
     )
     try:
         history.object_repr = repr(self)
     except Exception:
         history.object_repr = "(unknown)"
     history.save()
예제 #14
0
 def log_deletion(self, request, obj, object_repr):
     """
     Log that an object will be deleted. Note that this method is called
     before the deletion.
 """
     from django.contrib.admin.models import DELETION
     entry = LogEntry(user_id=request.user.id,
                      content_type_id=ContentType.objects.get_for_model(
                          self.model).pk,
                      object_id=smart_text(obj.pk),
                      object_repr=force_text(object_repr)[:200],
                      action_flag=DELETION)
     entry.save(using=request.database)
     return entry
예제 #15
0
 def log_addition(self, request, obj, message):
     """
 Log that an object has been successfully added.
 """
     from django.contrib.admin.models import ADDITION
     entry = LogEntry(
         user_id=request.user.pk,
         content_type_id=ContentType.objects.get_for_model(obj).pk,
         object_id=obj.pk,
         object_repr=force_text(obj)[:200],
         action_flag=ADDITION,
         change_message=message
         if isinstance(message, str) else json.dumps(message))
     entry.save(using=request.database)
     return entry
예제 #16
0
    def test_logentry_unicode(self):
        log_entry = LogEntry()

        log_entry.action_flag = ADDITION
        self.assertTrue(six.text_type(log_entry).startswith('Added '))

        log_entry.action_flag = CHANGE
        self.assertTrue(six.text_type(log_entry).startswith('Changed '))

        log_entry.action_flag = DELETION
        self.assertTrue(six.text_type(log_entry).startswith('Deleted '))

        # Make sure custom action_flags works
        log_entry.action_flag = 4
        self.assertEqual(six.text_type(log_entry), 'LogEntry Object')
예제 #17
0
 def log_addition(self, request, obj, message):
   """
   Log that an object has been successfully added.
   """
   from django.contrib.admin.models import ADDITION
   entry = LogEntry(
     user_id=request.user.pk,
     content_type_id=ContentType.objects.get_for_model(obj).pk,
     object_id=obj.pk,
     object_repr=force_text(obj)[:200],
     action_flag=ADDITION,
     change_message=message if isinstance(message, str) else json.dumps(message)
   )
   entry.save(using=request.database)
   return entry
예제 #18
0
 def log_deletion(self, request, obj, object_repr):
   """
       Log that an object will be deleted. Note that this method is called
       before the deletion.
   """
   from django.contrib.admin.models import DELETION
   entry = LogEntry(
     user_id=request.user.id,
     content_type_id=ContentType.objects.get_for_model(self.model).pk,
     object_id=smart_text(obj.pk),
     object_repr=force_text(object_repr)[:200],
     action_flag=DELETION
   )
   entry.save(using=request.database)
   return entry
예제 #19
0
 def log_change(self, request, obj, message):
   """
   Log that an object has been successfully changed.
   """
   if hasattr(obj, 'new_pk'):
     # We are renaming an existing object.
     # a) Save the new record in the right database
     old_pk = obj.pk
     obj.pk = obj.new_pk
     obj.save(using=request.database)
     # b) All linked fields need updating.
     for related in obj._meta.get_all_related_objects():
       related.model._base_manager.using(request.database) \
         .filter(**{related.field.name: old_pk}) \
         .update(**{related.field.name: obj})
     # c) Move the comments and audit trail to the new key
     model_type = ContentType.objects.get_for_model(obj)
     Comment.objects.using(request.database) \
       .filter(content_type__pk=model_type.id, object_pk=old_pk) \
       .update(object_pk=obj.pk)
     LogEntry.objects.using(request.database) \
       .filter(content_type__pk=model_type.id, object_id=old_pk) \
       .update(object_id=obj.pk)
     # e) Delete the old record
     self.queryset(request).get(pk=old_pk).delete()
   LogEntry(
     user_id=request.user.pk,
     content_type_id=ContentType.objects.get_for_model(obj).pk,
     object_id=smart_text(obj.pk),
     object_repr=force_text(obj)[:200],
     action_flag=CHANGE,
     change_message=message
   ).save(using=request.database)
예제 #20
0
def log_entry_change(user, model, beschreibung, message, object_id=None, action_time=None):
    content_type_id = ContentType.objects.get(app_label="fahrtenliste_main", model=model).pk

    action_time = action_time if action_time else timezone.now()

    entry = LogEntry(
        action_time=action_time,
        user_id=user.pk,
        content_type_id=content_type_id,
        object_id=object_id,
        object_repr=beschreibung,
        action_flag=CHANGE,
        change_message=message,
    )
    entry.save(force_insert=True)
    return LOG_ENTRY_STAUS_NEW, entry.id
예제 #21
0
 def history_view(self, request, object_id, extra_context=None):
     "The 'history' admin view for this model."
     from django.contrib.admin.models import LogEntry
     model = self.model
     opts = model._meta
     app_label = opts.app_label
     action_list = LogEntry.all().filter('object_id =', object_id).filter(
         'content_type =', ContentType.objects.get_for_model(model).id
     ).order('action_time').fetch(301)
     # If no history was found, see whether this object even exists.
     obj = get_object_or_404(model, object_id)
     context = {
         'title': _('Change history: %s') % force_unicode(obj),
         'action_list': action_list,
         'module_name': capfirst(force_unicode(opts.verbose_name_plural)),
         'object': obj,
         'root_path': self.admin_site.root_path,
         'app_label': app_label,
     }
     context.update(extra_context or {})
     return render_to_response(self.object_history_template or [
         "admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()),
         "admin/%s/object_history.html" % app_label,
         "admin/object_history.html"
     ], context, context_instance=template.RequestContext(request))
예제 #22
0
 def test_object_link(self):
     """Test the admin link to the log entry object."""
     log_entry = LogEntry(
         user=self.admin_user, action_flag=ADDITION,
         content_type_id=ContentType.objects.get_for_model(User).id,
         object_id=self.admin_user.id, object_repr=str(self.admin_user),
     )
     self.assertEqual(
         self.logentry_admin.object_link(log_entry),
         '<a href="{}">{}</a>'.format(log_entry.get_admin_url(), log_entry.object_repr)
     )
     # Test that a DELETION log entry returns object without a link
     log_entry.action_flag = DELETION
     self.assertEqual(
         self.logentry_admin.object_link(log_entry), log_entry.object_repr
     )
예제 #23
0
 def get_comment(self):
     try:
         return LogEntry(change_message=self.comment).get_change_message()
     except AttributeError:
         # Django < 1.10
         # LogEntry dont have `.get_change_message()`
         return self.comment
def test_object_link_no_reverse(admin, admin_user):
    log_entry = LogEntry(
        content_type_id=ContentType.objects.get(model='session').id,
        action_flag=CHANGE,
        object_id=5,
        object_repr='OBJ_REPR')
    assert admin.object_link(log_entry) == 'OBJ_REPR'
예제 #25
0
def run_query(request, query_id):
    query = Query.objects.get(id=query_id)
    text = query.prepare_text()
    params = []
    for param in query.dicovery_params():
        params.append(request.POST[param])

    cursor = connections[query.database].cursor()
    cursor.execute(text, params)
    lines = []
    for line in cursor.fetchall():
        lines.append([unicode(tup) for tup in line])

    if lines:
        response = {
            'template': '#table-response',
            'columns': [col[0] for col in cursor.description],
            'lines': lines
        }
    else:
        response = {'template': '#message-response', 'message': 'No data'}
    cursor.close()
    LogEntry(
        user=request.user,
        content_type=ContentType.objects.get_for_model(query),
        object_id=query.id,
        object_repr=force_unicode(query),
        change_message="run with %s" % ', '.join([
            '%s:%s' % (key, value) for key, value in request.POST.items()
            if key != 'csrfmiddlewaretoken'
        ]),
        action_flag=2  #change
    ).save()
    return HttpResponse(simplejson.dumps(response),
                        mimetype='application/json')
예제 #26
0
파일: views.py 프로젝트: kahihia/movements
def vet_user(request, user_id):
    user = User.objects.get(pk=user_id)
    try:
        rating = OrganisationalRating.objects.get(user=user)
    except OrganisationalRating.DoesNotExist:
        rating = None
    msg = ''
    if request.method == 'POST':
        form = VettingForm(request.POST, instance=rating)
        group_form = UserGroupForm(request.POST, instance=user)
        msg = None
        if form.is_valid() and group_form.is_valid():
            if not rating:
                rating = form.save(commit=False)
                rating.user_id = user.id
                rating.save()
            else:
                form.save()
            group_form.save()
            user.save()
            typeuser = ContentType.objects.filter(name='user').all()[0]
            log = LogEntry(user_id=request.user.id,
                           content_type=typeuser,
                           object_id=user.id,
                           object_repr=user.username,
                           action_flag=2,
                           change_message="vetted")
            log.save()
            msg = 'User updated'
    else:
        form = VettingForm(instance=rating)
        group_form = UserGroupForm(instance=user)
    email_verified = EmailAddress.objects.filter(user=user,
                                                 verified=True).exists()
    ctx = {
        'email_verified': email_verified,
        'original': user,
        'user': user,
        'form': form,
        'group_form': group_form,
        'msg': msg,
        'vetted': user.is_active
    }
    return render_to_response('admin/auth/user/vet_user.html',
                              ctx,
                              context_instance=RequestContext(request))
예제 #27
0
    def test_simpl_model(self):
        user = UserFactory()
        game = GameFactory(slug="blackjack")
        log_entry = LogEntry()

        self.assertTrue(events.simpl_model(user))
        self.assertTrue(events.simpl_model(game))
        self.assertFalse(events.simpl_model(log_entry))
def test_user_link(admin_user):
    admin = LogEntryAdmin(LogEntry, AdminSite())
    logentry = LogEntry(object_repr='OBJ_REPR',
                        action_flag=DELETION,
                        user_id=admin_user.id)

    assert '<a href="' in admin.user_link(logentry)
    assert admin_user.username in admin.user_link(logentry)
def test_object_link(admin, admin_user):
    log_entry = LogEntry(
        content_type_id=ContentType.objects.get_for_model(User).id,
        action_flag=ADDITION,
        object_id=admin_user.id,
        object_repr='OBJ_REPR')
    assert 'OBJ_REPR' in admin.object_link(log_entry)
    assert '<a href="' in admin.object_link(log_entry)
    def test_contrib_models(self):
        from django.contrib.admin.models import LogEntry
        from django.contrib.auth.models import User, Group, Permission

        self.assertTrue(is_shared_model(User()))
        self.assertTrue(is_shared_model(Permission()))
        self.assertTrue(is_shared_model(Group()))
        self.assertTrue(is_shared_model(LogEntry()))
예제 #31
0
    def _create_log_entry(self, action):
        if threadlocals.get_current_user().is_anonymous():
            user = User.objects.get(username='******')
        else:
            user = threadlocals.get_current_user()
        key = (self.__class__._meta.app_label,
               self.__class__._meta.object_name, self.pk)
        history = threadlocals.get_log_entry(key)
        if not history:
            history = LogEntry(
                user=user,
                object_id=self.pk,
                action_flag=action,
                content_type=ContentType.objects.get_for_model(self))
            threadlocals.set_log_entry(key, history)
        l = getattr(self, '_field_change_message_list', []) + getattr(
            self, '_field_m2m_change_message_list', [])
        if not l:
            return
        history.change_message = '\n'.join(l)
        try:
            history.object_repr = unicode(self)[:200]
        except Exception:
            history.object_repr = "(unknown)"

        history.save()
예제 #32
0
파일: models.py 프로젝트: dtarasiuk/zdjango
def deletesignal(sender, ** kwargs):
    #if issubclass(sender, UserInfo) or issubclass(sender, Counter):
        #couse fixtures initial problem
    try:
        instance = kwargs['instance']
        object_id = instance.id
        object_repr = instance.__unicode__()
        action_flag = DELETE
        content_type = ContentType.objects.get(name="log entry")
        user = User.objects.all()[0]
        log_entry = LogEntry(object_id=object_id, \
                             object_repr=object_repr, \
                             action_flag=action_flag, \
                             content_type=content_type, \
                             user=user)
        log_entry.save()
    except:
        pass
예제 #33
0
 def log_change(self, request, object, message):
     if is_active():
         if isinstance(message, list):
             set_comment(
                 LogEntry(change_message=json.dumps(
                     message)).get_change_message())
         else:
             set_comment(message)
     super(VersionAdmin, self).log_change(request, object, message)
예제 #34
0
def logentry_instance(msg, authorizer, model_type, model_object, flag=CHANGE):
    return LogEntry(
        user_id=authorizer.pk,
        content_type=ContentType.objects.get_for_model(model_type),
        object_id=model_object.pk,
        object_repr=str(model_object),
        change_message=msg,
        action_flag=flag,
    )
예제 #35
0
 def test_action_message(self):
     """Test getting the action message."""
     log_entry = LogEntry(
         user=self.admin_user, action_flag=ADDITION,
         content_type_id=ContentType.objects.get_for_model(User).id,
         object_id=self.admin_user.id, object_repr=str(self.admin_user),
     )
     # Ensure a log entry without a change message uses the action flag label
     self.assertEqual(
         self.logentry_admin.action_message(log_entry),
         '{}.'.format(log_entry.get_action_flag_display())
     )
     # Ensure a log entry with a change message is used for the action message
     change_message = 'This is a change message'
     log_entry.change_message = change_message
     self.assertEqual(
         self.logentry_admin.action_message(log_entry), change_message
     )
예제 #36
0
 def log_change(self, request, obj, message):
     """
     Log that an object has been successfully changed.
     """
     if hasattr(obj, "new_pk"):
         # We are renaming an existing object.
         # a) Save the new record in the right database
         old_pk = obj.pk
         obj.pk = obj.new_pk
         obj.save(using=request.database)
         # b) All linked fields need updating.
         for related in obj._meta.get_fields():
             if (
                 (related.one_to_many or related.one_to_one)
                 and related.auto_created
                 and not related.concrete
             ):
                 related.related_model._base_manager.using(request.database).filter(
                     **{related.field.name: old_pk}
                 ).update(**{related.field.name: obj})
         # c) Move the comments and audit trail to the new key
         model_type = ContentType.objects.get_for_model(obj)
         Comment.objects.using(request.database).filter(
             content_type__pk=model_type.id, object_pk=old_pk
         ).update(object_pk=obj.pk)
         LogEntry.objects.using(request.database).filter(
             content_type__pk=model_type.id, object_id=old_pk
         ).update(object_id=obj.pk)
         # d) Delete the old record
         obj.pk = old_pk
         obj.delete(using=request.database)
         obj.pk = obj.new_pk
     if isinstance(message, list):
         message = json.dumps(message)
     entry = LogEntry(
         user_id=request.user.pk,
         content_type_id=ContentType.objects.get_for_model(obj).pk,
         object_id=str(obj.pk),
         object_repr=str(obj)[:200],
         action_flag=CHANGE,
         change_message=message,
     )
     entry.save(using=request.database)
     return entry
예제 #37
0
파일: views.py 프로젝트: Utsira/movements
def vet_user(request, user_id):
    user = User.objects.get(pk=user_id)
    try:
        rating = OrganisationalRating.objects.get(user=user)
    except OrganisationalRating.DoesNotExist:
        rating = None
    msg = ''
    if request.method == 'POST':
        form = VettingForm(request.POST, instance=rating)
        group_form = UserGroupForm(request.POST, instance=user)
        msg = None
        if form.is_valid() and group_form.is_valid():
            if not rating:
                rating = form.save(commit=False)
                rating.user_id = user.id
                rating.save()
            else:
                form.save()
            group_form.save()
            user.save()
            typeuser = ContentType.objects.filter(name='user').all()[0]
            log = LogEntry(user_id=request.user.id,
                           content_type=typeuser,
                           object_id=user.id,
                           object_repr=user.username,
                           action_flag=2,
                           change_message="vetted")
            log.save()
            msg = 'User updated'
    else:
        form = VettingForm(instance=rating)
        group_form = UserGroupForm(instance=user)
    email_verified = EmailAddress.objects.filter(user=user, verified=True).exists()
    ctx = {
        'email_verified': email_verified,
        'original': user,
        'user': user,
        'form': form,
        'group_form': group_form,
        'msg': msg,
        'vetted': user.is_active
    }
    return render_to_response('admin/auth/user/vet_user.html', ctx, context_instance=RequestContext(request))
예제 #38
0
 def log_addition(self, request, obj):
     """
 Log that an object has been successfully added.
 """
     from django.contrib.admin.models import ADDITION
     LogEntry(user_id=request.user.pk,
              content_type_id=ContentType.objects.get_for_model(obj).pk,
              object_id=smart_text(obj.pk),
              object_repr=force_text(obj)[:200],
              action_flag=ADDITION).save(using=request.database)
def test_object_link_content_type_none(admin, admin_user):
    """
    Test reversion when content type is None (e.g. after deleting stale ones)

    Regression test for issue #21
    """
    log_entry = LogEntry(content_type_id=None,
                         action_flag=ADDITION,
                         object_id=admin_user.id,
                         object_repr='OBJ_REPR')
    assert admin.object_link(log_entry) == 'OBJ_REPR'
예제 #40
0
def log_deletion(sender, **kwargs):
    if not (issubclass(sender, LogEntry) or issubclass(sender, Session)):
        instance = kwargs["instance"]
        if not isinstance(instance, Session):
            try:
                usr = User.objects.all()[0]
                try:
                    rpr = instance.__unicode__()
                except:
                    rpr = repr(instance)
                content_type = ContentType.objects.get(
                    app_label=instance._meta.app_label, model=instance._meta.module_name
                )
                action_flag = DELETION
                log_entry = LogEntry(
                    object_id=instance.id, object_repr=rpr, action_flag=action_flag, content_type=content_type, user=usr
                )
                log_entry.save()
            except:
                pass
예제 #41
0
    def log_change(self, request, object, message, old_object=None):
        """
        Log that an object has been successfully changed.

        The default implementation creates an admin LogEntry object.
        """
        entry = LogEntry()
        entry.user = request.user
        entry.content_type = ContentType.objects.get_for_model(object)
        entry.object_id = smart_unicode(object.pk)
        entry.object_repr = force_unicode(object)[:200]
        entry.action_flag = CHANGE
        entry.change_message = message
        entry.save()

        if old_object:
            entry_extend = models.LogEntryExtend()
            entry_extend.entry = entry
            entry_extend.data = old_object
            entry_extend.save()
예제 #42
0
 def _create_log_entry(self, action):
     if threadlocals.get_current_user() is None:
         return
         raise Exception("Please enable ThreadsLocal middleware")
     if threadlocals.get_current_user().is_anonymous():
         user = User.objects.get(pk=0) # feature: User with pk=0 supposed to be anonymous user
     else:
         user = threadlocals.get_current_user()
     if SAVE_THROUGH_ADMIN: 
         history = LogEntry.objects.get(user=user, object_id = self.pk, action_flag = action,
                         content_type = ContentType.objects.get_for_model(self)).latest()
     else:
         history = LogEntry(user=user, object_id = self.pk, action_flag = action,
                             content_type = ContentType.objects.get_for_model(self))
         try:
             history.object_repr = repr(self)
         except Exception:
             history.object_repr = "(unknown)"
         history.save()
     return history
예제 #43
0
파일: tests.py 프로젝트: bGN4/DjangoAzure
    def test_object_link(self):
        admin = LogEntryAdmin(LogEntry, AdminSite())
        deleted = LogEntry(object_repr='OBJ_REPR', action_flag=DELETION)
        self.assertEquals(admin.object_link(deleted), 'OBJ_REPR')

        created = LogEntry(
            content_type_id=ContentType.objects.get_for_model(User).id,
            action_flag=ADDITION,
            object_id=self.user.id,
            object_repr='OBJ_REPR'
        )
        self.assertIn('OBJ_REPR', admin.object_link(created))
        self.assertIn('<a href="', admin.object_link(created))

        no_reverse = LogEntry(
            content_type_id=ContentType.objects.get(model='session').id,
            action_flag=CHANGE,
            object_id=5,
            object_repr='OBJ_REPR'
        )
        self.assertEquals(admin.object_link(no_reverse), 'OBJ_REPR')
예제 #44
0
def control_edition_note(list_control_fields_edited,
                         note,
                         teacher_id=None,
                         supervisor_id=None):
    from .models import NoteControlEdition
    from django.contrib.admin.models import LogEntry
    from django.contrib.contenttypes.models import ContentType
    import json
    note_type = ContentType.objects.get(app_label='school', model='note')

    fields = []
    for register_edited in list_control_fields_edited:
        note_edited_control = NoteControlEdition()
        note_edited_control.note_id = note.id
        note_edited_control.edit_field = register_edited.get('field_name')
        note_edited_control.value_edit_field = register_edited.get('value')
        note_edited_control.supervisor_id = supervisor_id
        note_edited_control.save()

        key = fields_note_spanish[register_edited['field_name']]
        fields.append('{} - {}'.format(key, register_edited['value']))

    flag_add = NoteControlEdition.objects.filter(note_id=note.id).count()
    flag_add = 1 if flag_add <= 1 else 2
    django_log_entry = LogEntry()
    django_log_entry.object_id = note.id
    django_log_entry.object_repr = note.__str__()
    django_log_entry.action_flag = flag_add

    key_message = 'added' if flag_add <= 1 else 'changed'
    if key_message == 'added':
        change_message = {key_message: {}}
    else:
        change_message = {key_message: {'fields': fields}}

    django_log_entry.change_message = json.dumps([change_message])
    django_log_entry.content_type_id = note_type.id
    django_log_entry.user_id = supervisor_id or teacher_id

    django_log_entry.save()
예제 #45
0
 def _create_log_entry(self, action):
     if threadlocals.get_current_user() is None:
         return
         raise Exception("Please enable ThreadsLocal middleware")
     if threadlocals.get_current_user().is_anonymous():
         user = User.objects.get(
             pk=0)  # feature: User with pk=0 supposed to be anonymous user
     else:
         user = threadlocals.get_current_user()
     if SAVE_THROUGH_ADMIN:
         history = LogEntry.objects.get(
             user=user,
             object_id=self.pk,
             action_flag=action,
             content_type=ContentType.objects.get_for_model(self)).latest()
     else:
         history = LogEntry(
             user=user,
             object_id=self.pk,
             action_flag=action,
             content_type=ContentType.objects.get_for_model(self))
         try:
             history.object_repr = repr(self)
         except Exception:
             history.object_repr = "(unknown)"
         history.save()
     return history
예제 #46
0
    def items(self):
        log_list = LogEntry.objects.filter(
            content_type__app_label='dnd').order_by('-action_time').all()[:50]

        result = []

        for entry in log_list:
            if False:
                entry = LogEntry()

            change_message = entry.change_message
            url = None
            object_rep = entry.object_repr
            try:
                obj = entry.get_edited_object()
                object_rep = obj.__unicode__()
                url = obj.get_absolute_url()
            except Exception:
                pass

            result.append({
                'object_rep': object_rep,
                'change_message': change_message,
                'url': url,
                'is_addition': entry.is_addition(),
                'is_change': entry.is_change(),
                'is_deletion': entry.is_deletion(),
                'author': entry.user,
                'pub_date': entry.action_time
            })

        return result
예제 #47
0
 def log_change(self, request, obj, message):
   """
   Log that an object has been successfully changed.
   """
   if hasattr(obj, 'new_pk'):
     # We are renaming an existing object.
     # a) Save the new record in the right database
     old_pk = obj.pk
     obj.pk = obj.new_pk
     obj.save(using=request.database)
     # b) All linked fields need updating.
     for related in obj._meta.get_fields():
       if (related.one_to_many or related.one_to_one) and related.auto_created and not related.concrete:
         related.related_model._base_manager.using(request.database) \
           .filter(**{related.field.name: old_pk}) \
           .update(**{related.field.name: obj})
     # c) Move the comments and audit trail to the new key
     model_type = ContentType.objects.get_for_model(obj)
     Comment.objects.using(request.database) \
       .filter(content_type__pk=model_type.id, object_pk=old_pk) \
       .update(object_pk=obj.pk)
     LogEntry.objects.using(request.database) \
       .filter(content_type__pk=model_type.id, object_id=old_pk) \
       .update(object_id=obj.pk)
     # d) Delete the old record
     obj.pk = old_pk
     obj.delete(using=request.database)
     obj.pk = obj.new_pk
   entry = LogEntry(
     user_id=request.user.pk,
     content_type_id=ContentType.objects.get_for_model(obj).pk,
     object_id=smart_text(obj.pk),
     object_repr=force_text(obj)[:200],
     action_flag=CHANGE,
     change_message=message if isinstance(message, str) else json.dumps(message)
     )
   entry.save(using=request.database)
   return entry
예제 #48
0
파일: admin.py 프로젝트: balmaster/djbookru
    def log_change(self, request, object, message, old_object=None):
        """
        Log that an object has been successfully changed.

        The default implementation creates an admin LogEntry object.
        """
        entry = LogEntry()
        entry.user = request.user
        entry.content_type = ContentType.objects.get_for_model(object)
        entry.object_id = smart_unicode(object.pk)
        entry.object_repr = force_unicode(object)[:200]
        entry.action_flag = CHANGE
        entry.change_message = message
        entry.save()
        
        if old_object:
            entry_extend = LogEntryExtend()
            entry_extend.entry = entry
            entry_extend.data = old_object
            entry_extend.save()
예제 #49
0
    def _create_log_entry(self, action):
        if threadlocals.get_current_user().is_anonymous():
            user = User.objects.get(username='******')
        else:
            user = threadlocals.get_current_user()
        key = (self.__class__._meta.app_label,self.__class__._meta.object_name,self.pk)
        history = threadlocals.get_log_entry(key)
        if not history:
            history = LogEntry(user=user, object_id = self.pk, action_flag = action,
                            content_type = ContentType.objects.get_for_model(self))
            threadlocals.set_log_entry(key,history)
        l = getattr(self,'_field_change_message_list',[]) + getattr(self,'_field_m2m_change_message_list',[])
        history.change_message = '\n'.join(l)
        try:
            history.object_repr = unicode(self)
        except Exception:
            history.object_repr = "(unknown)"


        history.save()
예제 #50
0
 def test_action_flag_choices(self):
     tests = ((1, 'Addition'), (2, 'Change'), (3, 'Deletion'))
     for action_flag, display_name in tests:
         with self.subTest(action_flag=action_flag):
             log = LogEntry(action_flag=action_flag)
             self.assertEqual(log.get_action_flag_display(), display_name)
예제 #51
0
 def test_logentry_change_message_not_json(self):
     """LogEntry.change_message was a string before Django 1.10."""
     logentry = LogEntry(change_message='non-JSON string')
     self.assertEqual(logentry.get_change_message(), logentry.change_message)
예제 #52
0
    If we don't patch this, then a ``DatabaseError`` will occur because
    the tables could not be found.
    """
    schema = get_active_schema_name()
    return [
        inline(self.model, self.admin_site) for inline in self.inlines
        if schema or is_shared_model(inline.model)
    ]


admin.ModelAdmin.get_inline_instances = get_inline_instances

if not getattr(LogEntry, 'object_schema', None):
    # We can't use a proper foreign key, as it plays havoc with migrations.
    LogEntry.add_to_class(
        'object_schema_id',
        models.TextField(blank=True, null=True)
    )

    @receiver(models.signals.pre_save, sender=LogEntry)
    def update_object_schema(sender, instance, **kwargs):
        obj = instance.get_edited_object()

        if not is_shared_model(obj):
            instance.object_schema_id = obj._schema

    get_admin_url = LogEntry.get_admin_url

    def get_admin_url_with_schema(self):
        url = get_admin_url(self)

        if self.object_schema_id and url:
예제 #53
0
파일: models.py 프로젝트: dedkovd/record
def auth_log(message, user = None):
  if user == None:
    user = User.objects.get(pk = 1)

  entry = LogEntry(user = user, object_repr = message, action_flag = 4)
  entry.save()