簡體   English   中英

Django ProfileListView 的測試失敗並出現 ValueError:無法分配“<SimpleLazyObject:....> &quot;: &quot;Profile.user&quot; 必須是 &quot;User&quot; 實例

[英]Test of Django ProfileListView fails with ValueError: Cannot assign "<SimpleLazyObject:....>": "Profile.user" must be a "User" instance

我是 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. 正確的登錄用戶
  2. 正確的非員工個人資料查詢集一旦我嘗試以下操作,我的測試就會中斷:
        response = self.client.get('/accounts/profiles/')

我知道我需要將用戶/個人資料數據傳遞給客戶端,但我不知道該怎么做。 由於context['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

如何模擬創建多個用戶/配置文件、登錄其中一個並獲取相關數據? 提前非常感謝。

這是一個非常具體的問題,我非常懷疑有人會看這個答案,但以防萬一:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM