Как использовать `construct_change_message` для создания` change_message` в моем собственном представлении для регистрации моих действий во встроенной модели `LogEntry`? В django - PullRequest
1 голос
/ 24 сентября 2019

Я добавил код в моем представлении, чтобы регистрировать каждое ADDITION действие на моей странице add_new_staff.Вот код:

            message = f'New user added. Added staff profile for {user.first_name} {user.last_name}'

            log = LogEntry.objects.log_action(
                user_id=request.user.id,
                content_type_id=ContentType.objects.get_for_model(user).pk,
                object_id=repr(user.id),
                # or any field you wish to represent here
                object_repr=repr(user.username),
                action_flag=ADDITION,  # assuming it's a new object
                change_message=message,)  # a new user has been added

            log.save()

Здесь я только сделал специальное сообщение get через message строку.И я думаю, для этого add_staff_view это нормально.Но сейчас я работаю над своим ProfileUpdateView, а также мне нужно зарегистрировать это CHANGE действие.Я видел, как страница изменения / обновления в администраторе django вставляет change_message в модель LogEntry (она показывает, какие поля изменены / обновляются), и я не могу придумать, как это сделать внутри моего собственного ProfileUpdateView.

Вот мой ProfileUpdateView:

@login_required
def ProfileUpdateView(request):
    if request.method == 'POST':
        user_form = accounts_forms.UserUpdateForm(request.POST, instance=request.user)
        if request.user.is_staff == True:
            profile_form = accounts_forms.StaffProfileUpdateForm(
                request.POST, instance=request.user.staffprofile)
        else:
            profile_form = accounts_forms.StudentProfileUpdateForm(
                request.POST, instance=request.user.studentprofile)

        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()

            log = LogEntry.objects.log_action(
                user_id=request.user.id,
                content_type_id=ContentType.objects.get_for_model(user).pk,
                object_id=repr(user.id),
                object_repr=str(user.username),
                action_flag=CHANGE,
                change_message = 'IM STUCK HERE',)

                log.save()

            messages.success(request, 'Your profile has been updated.')
            return redirect('update-profile')

    else:
        user_form = accounts_forms.UserUpdateForm(instance=request.user)
        if request.user.is_staff == True:
            profile_form = accounts_forms.StaffProfileUpdateForm(instance=request.user.staffprofile)
        else:
            profile_form = accounts_forms.StudentProfileUpdateForm(
                instance=request.user.studentprofile)
    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }
    return render(request, 'accounts/update_profile.html', context)

Любая помощь будет очень признательна, спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...