ImportError: cannot import name 'ProductDetails' from 'pages.views'

조회수 953회
읽지 않은 첫 메시지로 건너뛰기

Salima Begum

읽지 않음,
2020. 10. 16. 오전 1:27:5420. 10. 16.
받는사람 django...@googlegroups.com
Hi all,

I have written test case for views for details page. Here is below code I have written 

```
from django.test import RequestFactory
from django.urls import reverse
from django.contrib.auth.models import User
from pages.models import vk_customer
from mixer.backend.django import mixer
import pytest

from pages.views import ProductDetails


@pytest.mark.django_db
class TestViews:

    def test_product_detail_authenticated(self):
        mixer.blend('pages.vk_master_table')
        path = reverse('detail', kwargs={'pk': 1516})
        request = RequestFactory().get(path)
        request.user = mixer.blend(vk_customer)

        response = ProductDetails(request, pk=1516)
        print(response)
        assert response.status_code == 200
```
This the error i am getting.....
____________________________________________________________ ERROR collecting pages/tests/test_views.py ____________________________________________________________
ImportError while importing test module 'H:\vikreya\mysite\pages\tests\test_views.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
c:\users\user\appdata\local\programs\python\python38\lib\importlib\__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
pages\tests\test_views.py:8: in <module>
    from pages.views import ProductDetails
E   ImportError: cannot import name 'ProductDetails' from 'pages.views' (H:\vikreya\mysite\pages\views.py)

Please help me out to solve this error,

Thank you,
~Salima

Akinfolarin Stephen

읽지 않음,
2020. 10. 16. 오전 1:40:4020. 10. 16.
받는사람 django...@googlegroups.com
First I will like you to tell me the folder where test.py is and views.py

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMSz6bk187G0NSr%2Bza9RKAFnk475Z8nhxVRF%2BFk4iKtzwLXGxg%40mail.gmail.com.

Salima Begum

읽지 않음,
2020. 10. 16. 오전 2:42:0420. 10. 16.
받는사람 django...@googlegroups.com
projstructure.PNG

Salima Begum

읽지 않음,
2020. 10. 16. 오전 2:52:1420. 10. 16.
받는사람 django...@googlegroups.com
Hi all,

my project structure 
vikreya
mysite
.cache
.idea
.pytest_cache
logs
media
mysute
__init__.py
manage.py
settings.py
urls.py
wsgi.py
pages
.cache
migrations
static
templates
tests
test_views.py
__init__.py
admin.py
apps.py
cron.py
Forms.py
functions.py
models.py
urls.py
views.py

Salima Begum

읽지 않음,
2020. 10. 16. 오전 2:57:1920. 10. 16.
받는사람 django...@googlegroups.com
Hi all,
vikreya
    mysite
        .cache
        .idea
       .pytest_cache
    logs
    media
    mysite

            __init__.py
           manage.py
           settings.py
           urls.py
           wsgi.py
     pages
            .cache
            migrations
            static
            templates
            tests
                    test_views.py
                   __init__.py
            admin.py
            apps.py
            cron.py
            Forms.py
           functions.py
           models.py
          urls.py
          views.py

Shahprogrammer

읽지 않음,
2020. 10. 16. 오전 3:02:4320. 10. 16.
받는사람 Django users
Can you post your code of views.py
메시지가 삭제되었습니다.

Salima Begum

읽지 않음,
2020. 10. 16. 오전 3:11:1320. 10. 16.
받는사람 django...@googlegroups.com
urls.py

 path('ProductDetails/<int:id>', views.onClickSearch.ProductDetails, name='ProductDetails'),

views.py


class onClickSearch():

    def ProductDetails(request, id):
        try:
            email = request.session.get('email')
            proddtls = vk_master_table.objects.filter(id=id).first()
            if proddtls:
                banners = Extras().bestDeals_cat(proddtls.category_desc)

        # print(banners.product_name)
        except Exception as e:
            logging.error(e)
            return render(request, "ProductDetails.html", {'error': error, 'form': HomeForm(),
                                                           'time': settings.SESSION_IDLE_TIMEOUT,
                                                           'name': first_last_initial(email),
                                                           'msg_count': msg_count_cl(email),
                                                           'fullname': fullname(email), 'ProductDetails': proddtls,
                                                           'signinForm': SigninForm(), 'signupForm': CustomerForm()})
        return render(request, "ProductDetails.html", {'ProductDetails': proddtls, 'fbanners': banners,
                                                       'form': HomeForm(), 'signinForm': SigninForm(),
                                                       'name': first_last_initial(email),
                                                       'msg_count': msg_count_cl(email),
                                                       'fullname': fullname(email),
                                                       'time': settings.SESSION_IDLE_TIMEOUT,
                                                       'signupForm': CustomerForm()})




On Fri, Oct 16, 2020 at 12:32 PM Dhwanil Shah <dhwa...@gmail.com> wrote:
Can you post your views.py code



--
Dhwanil J Shah
Near Ashok agency, 
Madanwad ,
Valsad 396001

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

Akinfolarin Stephen

읽지 않음,
2020. 10. 16. 오전 3:58:4020. 10. 16.
받는사람 django...@googlegroups.com
The problem is you are trying to import views from where you have not created it I guess the page is  a folder then create the views.py inside of it

Salima Begum

읽지 않음,
2020. 10. 16. 오전 6:03:1120. 10. 16.
받는사람 django...@googlegroups.com
Inside pages folder I already have views.py 

Thanks
~salima

Shahprogrammer

읽지 않음,
2020. 10. 16. 오전 6:40:1720. 10. 16.
받는사람 Django users
You have created a class named  onClickSearch  with method  ProductDetails . So you can't import a method of a class. To use the method you need to import class.
So in place of importing  from pages.views import ProductDetails  in test_views.py do from pages.views import onClickSearch  & then use it's method as onClickSearch. ProductDetails   as per your need in your code 

Salima Begum

읽지 않음,
2020. 10. 16. 오전 7:47:3320. 10. 16.
받는사람 django...@googlegroups.com
Thank you for your reply

I did that again I am getting this error
___________________________________________________________ TestViews.test_product_detail_authenticated ____________________________________________________________

klass = <class 'pages.models.vk_ls_product_search'>, args = (), kwargs = {'pk': 22}, queryset = <QuerySet [<vk_ls_product_search: QdlRuBGaIUoUrxhrJWzM>]>

    def get_object_or_404(klass, *args, **kwargs):
        """
        Use get() to return an object, or raise a Http404 exception if the object
        does not exist.

        klass may be a Model, Manager, or QuerySet object. All other passed
        arguments and keyword arguments are used in the get() query.

        Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
        one object is found.
        """
        queryset = _get_queryset(klass)
        if not hasattr(queryset, 'get'):
            klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
            raise ValueError(
                "First argument to get_object_or_404() must be a Model, Manager, "
                "or QuerySet, not '%s'." % klass__name
            )
        try:
>           return queryset.get(*args, **kwargs)

c:\users\user\appdata\local\programs\python\python38\lib\site-packages\django\shortcuts.py:76:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <QuerySet [<vk_ls_product_search: QdlRuBGaIUoUrxhrJWzM>]>, args = (), kwargs = {'pk': 22}, clone = <QuerySet []>, limit = 21, num = 0

    def get(self, *args, **kwargs):
        """
        Perform the query and return a single object matching the given
        keyword arguments.
        """
        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
        if self.query.can_filter() and not self.query.distinct_fields:
            clone = clone.order_by()
        limit = None
        if not clone.query.select_for_update or connections[clone.db].features.supports_select_for_update_with_limit:
            limit = MAX_GET_RESULTS
            clone.query.set_limits(high=limit)
        num = len(clone)
        if num == 1:
            return clone._result_cache[0]
        if not num:
>           raise self.model.DoesNotExist(
                "%s matching query does not exist." %
                self.model._meta.object_name
            )
E           pages.models.vk_ls_product_search.DoesNotExist: vk_ls_product_search matching query does not exist.

c:\users\user\appdata\local\programs\python\python38\lib\site-packages\django\db\models\query.py:415: DoesNotExist

During handling of the above exception, another exception occurred:

self = <test_views.TestViews object at 0x0000003BBE75DA00>

    def test_product_detail_authenticated(self):
        mixer.blend('pages.vk_ls_product_search')
        path = reverse('ProductDetails_ls', kwargs={'pk': 22})

        request = RequestFactory().get(path)
        request.user = mixer.blend(vk_customer)

>       response = onClickSearch.ProductDetails_ls(request, pk=22)

pages\tests\test_views.py:18:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
pages\views.py:2795: in ProductDetails_ls
    product_ls = get_object_or_404(vk_ls_product_search, pk=pk)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

klass = <class 'pages.models.vk_ls_product_search'>, args = (), kwargs = {'pk': 22}, queryset = <QuerySet [<vk_ls_product_search: QdlRuBGaIUoUrxhrJWzM>]>

    def get_object_or_404(klass, *args, **kwargs):
        """
        Use get() to return an object, or raise a Http404 exception if the object
        does not exist.

        klass may be a Model, Manager, or QuerySet object. All other passed
        arguments and keyword arguments are used in the get() query.

        Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
        one object is found.
        """
        queryset = _get_queryset(klass)
        if not hasattr(queryset, 'get'):
            klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
            raise ValueError(
                "First argument to get_object_or_404() must be a Model, Manager, "
                "or QuerySet, not '%s'." % klass__name
            )
        try:
            return queryset.get(*args, **kwargs)
        except queryset.model.DoesNotExist:
>           raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
E           django.http.response.Http404: No vk_ls_product_search matches the given query.

c:\users\user\appdata\local\programs\python\python38\lib\site-packages\django\shortcuts.py:78: Http404


Please can you help me to solve this error too , Thank you


전체답장
작성자에게 답글
전달
새 메시지 0개