Django profileListView的测试因ValueError而失败:无法分配“ SimplelazyObject:....>:&quot” profile.user.user;必须是“用户”实例

发布于 2025-01-23 14:57:32 字数 6884 浏览 0 评论 0原文

我是Django的初学者和新手,如果这个问题对某些人来说很愚蠢,对不起。 我正在努力进行集成测试。 在我的应用中,我有一对一的用户/个人资料关系。我有一个列表视图来显示注册用户的个人资料数据:

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. 正确登录的用户
  2. 正确的非员工profiles的QuerySet 一旦尝试类似的事情,我的测试就会中断:
        response = self.client.get('/accounts/profiles/')

我知道我需要将用户/个人资料数据传递给客户端,但我无法弄清楚如何做到这一点。看起来由于上下文['Current_Profile'] = profile.objects.get(pk = self.request.user.pk),看起来它失败了。

整个“测试”如下:

    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/')

它失败了:

/home/kk/Documents/Github/Phonotheque/venv/bin/python /snap/pycharm-professional/280/plugins/python/helpers/pycharm/django_test_manage.py test Phonotheque.accounts_app.tests.views.test_ProfileListView.ProfilesListViewTests.test_view_get_context_data__should_return_correct_context /home/kk/Documents/Github/Phonotheque
Testing started at 15:54 ...
Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).


/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/views/generic/list.py:91: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'Phonotheque.accounts_app.models.Profile'> QuerySet.
  return self.paginator_class(
Destroying test database for alias 'default'...





Error
Traceback (most recent call last):
  File "/home/kk/Documents/Github/Phonotheque/Phonotheque/accounts_app/views.py", line 138, in get_context_data
    context['current_profile'] = Profile.objects.get(pk=self.request.user.pk)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/query.py", line 496, in get
    raise self.model.DoesNotExist(
Phonotheque.accounts_app.models.Profile.DoesNotExist: Profile matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/kk/Documents/Github/Phonotheque/Phonotheque/accounts_app/tests/views/test_ProfileListView.py", line 65, in test_view_get_context_data__should_return_correct_context
    response = self.client.get('/accounts/profiles/')
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 836, in get
    response = super().get(path, data=data, secure=secure, **extra)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 424, in get
    return self.generic(
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 541, in generic
    return self.request(**r)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 810, in request
    self.check_exception(response)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 663, in check_exception
    raise exc_value
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 119, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/views/generic/list.py", line 174, in get
    context = self.get_context_data()
  File "/home/kk/Documents/Github/Phonotheque/Phonotheque/accounts_app/views.py", line 140, in get_context_data
    Profile.objects.create(user=self.request.user)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/query.py", line 512, in create
    obj = self.model(**kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/base.py", line 541, in __init__
    _setattr(self, field.name, rel_obj)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 338, in __set__
    super().__set__(instance, value)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 235, in __set__
    raise ValueError(
ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f682f11e220>>": "Profile.user" must be a "User" instance.



Process finished with exit code 1

如何模拟多个用户/配置文件的创建,登录其中一个并获取相关数据? 非常感谢。

I am a Django beginner and a SOF newbie, sorry if this question sounds a silly to some.
I am struggling with my integration tests.
In my app I have a one-to-one User/Profile relationship. I have a list view to show registered users' profile data:

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

I want to test the get_context_data() method to ensure it returns:

  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.

The whole 'test' is below:

    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/')

It fails with:

/home/kk/Documents/Github/Phonotheque/venv/bin/python /snap/pycharm-professional/280/plugins/python/helpers/pycharm/django_test_manage.py test Phonotheque.accounts_app.tests.views.test_ProfileListView.ProfilesListViewTests.test_view_get_context_data__should_return_correct_context /home/kk/Documents/Github/Phonotheque
Testing started at 15:54 ...
Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).


/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/views/generic/list.py:91: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'Phonotheque.accounts_app.models.Profile'> QuerySet.
  return self.paginator_class(
Destroying test database for alias 'default'...





Error
Traceback (most recent call last):
  File "/home/kk/Documents/Github/Phonotheque/Phonotheque/accounts_app/views.py", line 138, in get_context_data
    context['current_profile'] = Profile.objects.get(pk=self.request.user.pk)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/query.py", line 496, in get
    raise self.model.DoesNotExist(
Phonotheque.accounts_app.models.Profile.DoesNotExist: Profile matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/kk/Documents/Github/Phonotheque/Phonotheque/accounts_app/tests/views/test_ProfileListView.py", line 65, in test_view_get_context_data__should_return_correct_context
    response = self.client.get('/accounts/profiles/')
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 836, in get
    response = super().get(path, data=data, secure=secure, **extra)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 424, in get
    return self.generic(
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 541, in generic
    return self.request(**r)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 810, in request
    self.check_exception(response)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/test/client.py", line 663, in check_exception
    raise exc_value
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 119, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/views/generic/list.py", line 174, in get
    context = self.get_context_data()
  File "/home/kk/Documents/Github/Phonotheque/Phonotheque/accounts_app/views.py", line 140, in get_context_data
    Profile.objects.create(user=self.request.user)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/query.py", line 512, in create
    obj = self.model(**kwargs)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/base.py", line 541, in __init__
    _setattr(self, field.name, rel_obj)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 338, in __set__
    super().__set__(instance, value)
  File "/home/kk/Documents/Github/Phonotheque/venv/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 235, in __set__
    raise ValueError(
ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f682f11e220>>": "Profile.user" must be a "User" instance.



Process finished with exit code 1

How do I simulate creation of multiple users/profiles, logging in of one of them and obtaining the relevant data?
Thanks a lot in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红ご颜醉 2025-01-30 14:57:32

这是一个非常具体的问题,我非常怀疑任何人都会看这个答案,但以防万一:

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)

It was quite a specific question and I very much doubt anyone ever will be looking at this answer but just in case:

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文