Тест Django ProfileListView завершается с ошибкой ValueError: Невозможно присвоить "<SimpleLazyObject:....>": "Profile.user" должен быть экземпляром "User".

Я новичок в Django и новичок в SOF, извините, если этот вопрос покажется кому-то глупым. Я испытываю трудности с интеграционными тестами. В моем приложении у меня есть отношения "один к одному" пользователь/профиль. У меня есть представление списка для отображения данных профиля зарегистрированных пользователей:

class ProfileListView(views.ListView, LoginRequiredMixin):
    model = Profile
    template_name = 'registration/profile_list.html'
    paginate_by = 8

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(ProfileListView, self).get_context_data()

        # superuser raises DoesNotExist at /accounts/profiles/ as they are created with createsuperuser in manage.py
        # hence are not assigned a profile automatically => create profile for them here
        try:
            context['current_profile'] = Profile.objects.get(pk=self.request.user.pk)
        except ObjectDoesNotExist:
            Profile.objects.create(user=self.request.user)
            context['current_profile'] = Profile.objects.get(pk=self.request.user.pk)
        # get all other users' profiles apart from staff and current user
        regular_users = User.objects \
            .filter(is_superuser=False, is_staff=False, is_active=True) \
            .exclude(pk=self.request.user.pk)
        context['non_staff_active_profiles'] = Profile.objects.filter(user__in=regular_users)

        return context

Я хочу проверить метод get_context_data(), чтобы убедиться, что он возвращает:

  1. correct logged in user
  2. correct queryset of non-staff profiles My test breaks as soon as I try something like:
        response = self.client.get('/accounts/profiles/')

I understand I need to pass user/profile data to the client but I could not figure out how to do that. It looks like it fails because of context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) and I have no idea why.

Весь "тест" приведен ниже:

    def test_view_get_context_data__should_return_correct_context(self):
        new_user = User.objects.create_user(**self.VALID_USER_DATA_1)
        # create profile
        new_profile = Profile.objects.create(user=new_user)
        # test profile
        self.assertEqual(new_profile.user_id, new_user.pk)

        response = self.client.get('/accounts/profiles/')

Не получается при:

Как смоделировать создание нескольких пользователей/профилей, вход в один из них и получение соответствующих данных? Заранее большое спасибо.

Это был довольно специфический вопрос, и я очень сомневаюсь, что кто-то когда-либо будет смотреть на этот ответ, но на всякий случай:

def test_view_get_context_data__with__logged_in_user_should_return_correct_context(self):
        user_data = {'username': 'BayHuy', 'password': '11111111', }
        new_user = User.objects.create_user(**user_data)

        new_profile = Profile.objects.create(user=new_user)

        self.assertEqual(len(User.objects.all()), 1)
        self.assertEqual(new_profile.user_id, new_user.pk)
        self.assertEqual(len(Profile.objects.all()), 1)

        self.client.login(**user_data)

        response = self.client.get(reverse('profiles-list'))

        self.assertEqual(
            new_profile,
            response.context_data['current_profile'])

        self.assertEqual(
            new_profile, response.context_data['current_profile'])

        self.assertEqual(len(response.context_data['profile_list']), 1)

Вернуться на верх