Python reversion.revisions.set_user() Examples

The following are 14 code examples of reversion.revisions.set_user(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module reversion.revisions , or try the search function .
Example #1
Source File: views.py    From anytask with MIT License 6 votes vote down vote up
def ajax_change_status(request):
    if not request.is_ajax():
        return HttpResponseForbidden()

    post_dict = dict(request.POST)
    if 'statuses_id[]' in post_dict and 'profile_ids[]' in post_dict:
        statuses = UserStatus.objects.filter(id__in=post_dict['statuses_id[]'])
        for profile in UserProfile.objects.filter(id__in=post_dict['profile_ids[]']):
            for status in statuses:
                profile.set_status(status)

            post_save.send(UserProfile, instance=profile, created=False)
            reversion.set_user(request.user)
            reversion.set_comment("Change from user status bulk change")

    return HttpResponse("OK") 
Example #2
Source File: social_auth.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
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_default_language()
            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.html', {
            'title': 'Create your profile', 'form': form,
        }) 
Example #3
Source File: views.py    From anytask with MIT License 5 votes vote down vote up
def lesson_create(request, course):
    user = request.user
    params = get_params(request.POST, user)
    for group in params['lesson_groups']:
        schedule_id = uuid.uuid1().hex
        for lssn_date in params['lesson_dates']:
            lssn_id = set_params(params, course, group, user, schedule_id, lssn_date)

    reversion.set_user(user)
    reversion.set_comment("Create lesson")

    return HttpResponse(json.dumps({'page_title': ' | '.join([params['lesson_title'], course.name, str(course.year)]),
                                    'redirect_page': '/lesson/edit/' + str(lssn_id)}),
                        content_type="application/json") 
Example #4
Source File: views.py    From anytask with MIT License 5 votes vote down vote up
def lesson_edit(request, course, lesson_id):
    user = request.user
    lesson = get_object_or_404(Lesson, id=lesson_id)
    schedule_id = lesson.schedule_id
    group = lesson.group
    params = get_params(request.POST, request.user)

    if 'change_all' not in request.POST:
        set_params(params, course, group, user, schedule_id, params['lesson_dates'][0], lesson)
    else:
        if need_delete(lesson, params):
            Lesson.objects.filter(
                schedule_id=schedule_id,
                date_starttime__gte=lesson.date_starttime
            ).delete()
            for i, lssn_date in enumerate(params['lesson_dates']):
                set_params(params, course, group, user, schedule_id, lssn_date, None)

        else:
            lesson_changed = Lesson.objects.filter(
                schedule_id=schedule_id,
                date_starttime__gte=lesson.date_starttime
            )
            i = j = 0
            while i < len(lesson_changed):
                if lesson_changed[i].date_starttime.date() != params['lesson_dates'][j][0].date():
                    j += 1
                else:
                    set_params(params, course, group, user, schedule_id, params['lesson_dates'][j], lesson_changed[i])
                    i += 1

    reversion.set_user(user)
    reversion.set_comment("Edit lesson")

    return HttpResponse(json.dumps({'page_title': ' | '.join([lesson.title, course.name, str(course.year)]),
                                    'redirect_page': None}),
                        content_type="application/json") 
Example #5
Source File: views.py    From anytask with MIT License 5 votes vote down vote up
def my_tasks(request):
    user = request.user
    issues = Issue.objects \
        .filter(student=user) \
        .exclude(task__type=Task.TYPE_MATERIAL) \
        .exclude(task__type=Task.TYPE_SEMINAR) \
        .order_by('-update_time')

    user_as_str = str(user.username) + '_tasks_filter'

    f = IssueFilterStudent(request.GET, issues)
    f.set_user(user)

    if f.form.data:
        request.session[user_as_str] = f.form.data
    elif user_as_str in request.session:
        f.form.data = request.session.get(user_as_str)

    f.form.helper = FormHelper(f.form)
    f.form.helper.form_method = 'get'
    f.form.helper.layout.append(
        HTML(u"""<div class="form-group row">
        <button id="button_filter" class="btn btn-secondary pull-xs-right" type="submit">{0}</button>
        </div>""".format(_(u'primenit')))
    )

    context = {
        'filter': f,
    }

    return render(request, 'my_tasks.html', context) 
Example #6
Source File: comments.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
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:
            if len(parent) > 10:
                return HttpResponseBadRequest()
            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()
            return HttpResponseRedirect(request.path)

        context = self.get_context_data(object=self.object, comment_form=form)
        return self.render_to_response(context) 
Example #7
Source File: user.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_api_token(request):
    profile = request.profile
    with transaction.atomic(), revisions.create_revision():
        revisions.set_user(request.user)
        revisions.set_comment(_('Generated API token for user'))
        return JsonResponse({'data': {'token': profile.generate_api_token()}}) 
Example #8
Source File: user.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def remove_api_token(request):
    profile = request.profile
    with transaction.atomic(), revisions.create_revision():
        profile.api_token = None
        profile.save()
        revisions.set_user(request.user)
        revisions.set_comment(_('Removed API token for user'))
    return JsonResponse({}) 
Example #9
Source File: user.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_scratch_codes(request):
    profile = request.profile
    with transaction.atomic(), revisions.create_revision():
        revisions.set_user(request.user)
        revisions.set_comment(_('Generated scratch codes for user'))
    return JsonResponse({'data': {'codes': profile.generate_scratch_codes()}}) 
Example #10
Source File: comment.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def form_valid(self, form):
        with transaction.atomic(), revisions.create_revision():
            revisions.set_comment(_('Edited from site'))
            revisions.set_user(self.request.user)
            return super(CommentEditAjax, self).form_valid(form) 
Example #11
Source File: mixins.py    From django-project with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_revision(self, user, comment, *args, **kwargs):
        with transaction.atomic(), reversion.create_revision():
            self.save()
            reversion.set_user(user)
            reversion.set_comment(comment) 
Example #12
Source File: views.py    From anytask with MIT License 4 votes vote down vote up
def set_user_statuses(request, username=None):
    if request.method == 'GET':
        return HttpResponseForbidden()

    user = request.user

    if not user.is_staff:
        return HttpResponseForbidden()

    user_to_show = user
    if username:
        user_to_show = get_object_or_404(User, username=username)

    user_profile = user_to_show.profile
    is_error = False
    error = ''

    try:
        user_profile.user_status = filter(bool, dict(request.POST).get('status_by_type[]', []))
        user_profile.updated_by = user
        user_profile.save()
        reversion.set_user(user)
        reversion.set_comment("Change from user profile")
    except Exception as e:
        is_error = True
        error = unicode(e)

    user_statuses = list(user_profile.user_status.all().values("name", "color"))

    user_profile_log = {
        'update_time': user_profile.update_time.astimezone(
            timezone_pytz(user.profile.time_zone)
        ).strftime("%d-%m-%Y %H:%M"),
        'updated_by': user_profile.updated_by.username,
        'fullname': user_profile.updated_by.get_full_name()
    }

    return HttpResponse(json.dumps({'user_statuses': user_statuses,
                                    'user_profile_log': user_profile_log,
                                    'is_error': is_error,
                                    'error': error}),
                        content_type="application/json") 
Example #13
Source File: user.py    From online-judge with GNU Affero General Public License v3.0 4 votes vote down vote up
def edit_profile(request):
    if request.profile.mute:
        raise Http404()
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=request.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']])

            perm = Permission.objects.get(codename='test_site', content_type=ContentType.objects.get_for_model(Profile))
            if form.cleaned_data['test_site']:
                request.user.user_permissions.add(perm)
            else:
                request.user.user_permissions.remove(perm)

            return HttpResponseRedirect(request.path)
    else:
        form = ProfileForm(instance=request.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
        form.fields['test_site'].initial = request.user.has_perm('judge.test_site')

    tzmap = settings.TIMEZONE_MAP
    return render(request, 'user/edit-profile.html', {
        'require_staff_2fa': settings.DMOJ_REQUIRE_STAFF_2FA,
        'form': form, 'title': _('Edit profile'), 'profile': request.profile,
        'can_download_data': bool(settings.DMOJ_USER_DATA_DOWNLOAD),
        'has_math_config': bool(settings.MATHOID_URL),
        'TIMEZONE_MAP': tzmap or 'http://momentjs.com/static/img/world.png',
        'TIMEZONE_BG': settings.TIMEZONE_BG if tzmap else '#4E7CAD',
    }) 
Example #14
Source File: test_model_anonymization.py    From django-GDPR with MIT License 4 votes vote down vote up
def test_reversion_anonymization(self):
        from reversion import revisions as reversion
        from reversion.models import Version
        from gdpr.utils import get_reversion_versions

        anon = ContactFormAnonymizer()
        anon.Meta.anonymize_reversion = True
        anon.Meta.reversible_anonymization = True

        user = User(username='test_username')
        user.save()

        with reversion.create_revision():
            form = ContactForm()
            form.email = CUSTOMER__EMAIL
            form.full_name = CUSTOMER__LAST_NAME
            form.save()

            reversion.set_user(user)

        with reversion.create_revision():
            form.email = CUSTOMER__EMAIL2
            form.save()

            reversion.set_user(user)

        with reversion.create_revision():
            form.email = CUSTOMER__EMAIL3
            form.save()

            reversion.set_user(user)

        versions: List[Version] = get_reversion_versions(form)

        self.assertEqual(versions[0].field_dict['email'], CUSTOMER__EMAIL)
        self.assertEqual(versions[1].field_dict['email'], CUSTOMER__EMAIL2)
        self.assertEqual(versions[2].field_dict['email'], CUSTOMER__EMAIL3)

        anon.anonymize_obj(form, base_encryption_key=self.base_encryption_key)

        anon_versions: List[Version] = get_reversion_versions(form)
        anon_form = ContactForm.objects.get(pk=form.pk)

        self.assertNotEqual(anon_versions[0].field_dict['email'], CUSTOMER__EMAIL)
        self.assertNotEqual(anon_versions[1].field_dict['email'], CUSTOMER__EMAIL2)
        self.assertNotEqual(anon_versions[2].field_dict['email'], CUSTOMER__EMAIL3)
        self.assertNotEqual(anon_form.email, CUSTOMER__EMAIL3)

        anon.deanonymize_obj(anon_form, base_encryption_key=self.base_encryption_key)

        deanon_versions: List[Version] = get_reversion_versions(form)
        deanon_form = ContactForm.objects.get(pk=form.pk)

        self.assertEqual(deanon_versions[0].field_dict['email'], CUSTOMER__EMAIL)
        self.assertEqual(deanon_versions[1].field_dict['email'], CUSTOMER__EMAIL2)
        self.assertEqual(deanon_versions[2].field_dict['email'], CUSTOMER__EMAIL3)
        self.assertEqual(deanon_form.email, CUSTOMER__EMAIL3)
        self.assertDictEqual(versions[0].field_dict, deanon_versions[0].field_dict)
        self.assertDictEqual(versions[1].field_dict, deanon_versions[1].field_dict)
        self.assertDictEqual(versions[2].field_dict, deanon_versions[2].field_dict)