Django:无法获取get响应值AttributeError:模块'Django.http.request'没有属性'get'

2024-09-27 00:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个简单的应用程序,收集鞋子的数据,然后将其显示为列表。我想使用分页,使用Django的分页器非常简单。我的问题是,我无法让Django提供get请求中发送的值

根据Django docs我一直在做的应该是有效的。我已经用request和HttpRequest尝试过了,每次我都得到一个“no attribute”错误


    Traceback (most recent call last):
      File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
        self.run()
      File "/usr/lib/python3.9/threading.py", line 892, in run
        self._target(*self._args, **self._kwargs)
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
        fn(*args, **kwargs)
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
        self.check(display_num_errors=True)
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check
        all_issues = checks.run_checks(
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks
        new_errors = check(app_configs=app_configs, databases=databases)
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config
        return check_resolver(resolver)
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver
        return check_method()
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 412, in check
        for pattern in self.url_patterns:
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
        res = instance.__dict__[self.name] = self.func(instance)
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 598, in url_patterns
        patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
        res = instance.__dict__[self.name] = self.func(instance)
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
        return import_module(self.urlconf_name)
      File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
      File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
      File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 855, in exec_module
      File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
      File "/home/pjay/PycharmProjects/gettest/gettest/gettest/urls.py", line 21, in <module>
        path('', include('shoes.urls'), name='shoes_list'),
      File "/home/pjay/PycharmProjects/gettest/venv/lib/python3.9/site-packages/django/urls/conf.py", line 34, in include
        urlconf_module = import_module(urlconf_module)
      File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
      File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
      File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 855, in exec_module
      File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
      File "/home/pjay/PycharmProjects/gettest/gettest/shoes/urls.py", line 3, in <module>
        from . import views
      File "/home/pjay/PycharmProjects/gettest/gettest/shoes/views.py", line 7, in <module>
        class ShoeListView(ListView):
      File "/home/pjay/PycharmProjects/gettest/gettest/shoes/views.py", line 11, in ShoeListView
        if request.method == "GET":
    AttributeError: module 'django.http.request' has no attribute 'method'

下面是我在views.py文件中的代码

from django.views.generic import ListView
from django.http import HttpRequest, request

from .models import Shoes


class ShoeListView(ListView):
    model = Shoes
    template_name = 'shoes/shoes-list.html'
    context_object_name = 'shoes'
    if request.method == "GET":
        shoespp = request.GET['shoespp']
    else:
        shoespp = 2
    paginate_by = shoespp

这是我的模板

<body>
    <h1>Shoes</h1>
    <h2>List of Shoes</h2>
    <form method="get">
        <select name="shoespp">
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
        </select>
        <input type="submit" value="List Shoes">
    </form>

    <ul>
        {%for pair in shoes %}
        <li>
            <strong>{{ pair }} <em>{{ pair.brand }}</em></strong> <em>{{ pair.colorway }}</em> - {{ pair.size }}
        </li>
        {% endfor %}
    </ul>

    <p>
        {% if page_obj.has_previous %}
        <a href="?page=1"><button>&laquo; first</button></a>
        <a href="?page={{ page_obj.previous_page_number }}"><button>previous</button></a>
        {% endif %}

        <span>
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
        <a href="?page={{ page_obj.next_page_number }}"><button>next</button></a>
        <a href="?page={{ page_obj.paginator.num_pages }}"><button>last &raquo; </button></a>
        {% endif %}
    </p>
</body>

有人能告诉我哪里出了问题吗?我完全没有主意了,一直在寻找一个可能的答案,但没有成功。提前谢谢

编辑(带有解决方案代码)

感谢@furas为我的问题提供了解决方案。我想我现在明白出了什么问题。我为任何可能遇到类似问题的人提供解决方案代码

视图.py

    from django.views.generic import ListView
    
    from .models import Shoes
    
    
    class ShoeListView(ListView):
        model = Shoes
        template_name = 'shoes/shoes-list.html'
        context_object_name = 'shoes'
        paginate_by = 1
    
        def get_context_data(self, **kwargs):
            if 'shoespp' in self.request.GET:
                self.paginate_by = self.request.GET.get('shoespp', 2)
            shoes = super().get_context_data(**kwargs)
            shoes['last_shoespp'] = self.request.GET.get('shoespp')
            return shoes

模板文件.html

    <!DOCTYPE html>
    <html lang="en-au">
        <head>
            <title>Shoes List</title>
        </head>
    
        <body>
            <h1>Shoes</h1>
            <h2>List of Shoes</h2>
            <form method="GET">
                <select name="shoespp" action="">
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                </select>
                <input type="submit" value="List Shoes">
            </form>
    
            <h3>{{ shoespp }}</h3>
    
            <ul>
                {%for pair in shoes %}
                <li>
                    <strong>{{ pair }} <em>{{ pair.brand }}</em></strong> <em>{{ pair.colorway }}</em> - {{ pair.size }}
                </li>
                {% endfor %}
            </ul>
    
            <h3>{{ steps }}</h3>
    
            <p>
                {% if page_obj.has_previous %}
                <a href="?page=1{% if 'last_shoespp' != False %}&shoespp={{ last_shoespp }}{% endif %}">
                    <button>&laquo; first</button>
                </a>
                <a href="?page={{ page_obj.previous_page_number }}{% if 'last_shoespp' != False %}&shoespp={{ last_shoespp }}{% endif %}">
                    <button>previous</button>
                </a>
                {% endif %}
    
                <span>
                    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
                </span>
    
                {% if page_obj.has_next %}
                <a href="?page={{ page_obj.next_page_number }}{% if 'last_shoespp' != False %}&shoespp={{ last_shoespp }}{% endif %}">
                    <button>next</button>
                </a>
                <a href="?page={{ page_obj.paginator.num_pages }}{% if 'last_shoespp' != False %}&shoespp={{ last_shoespp }}{% endif %}">
                    <button>last &raquo;</button>
                </a>
                {% endif %}
            </p>
        </body>
    </html>

Tags: djangoinpyselfhomeliblinepage
1条回答
网友
1楼 · 发布于 2024-09-27 00:15:54

在您当前的代码中,它在开始时执行request.GET,甚至在它将HTML发送到浏览器之前,用户可以单击List shoes

我认为它应该在服务器从浏览器获得请求时执行的某个函数中

但是另一个问题可能是这个页面使用<form>发送GET,但是分页中的每个链接都是作为GET发送的,所以您可能需要检查shoespp是否真的是发送的

我不能测试它,但它可以是这样的

class ShoeListView(ListView):
    model = Shoes
    template_name = 'shoes/shoes-list.html'
    context_object_name = 'shoes'

    paginate_by = 2  # set some value at start

    def get_context_data(self, **kwargs):
        # change value when get new value from browser
        if 'shoespp' in self.request.GET:
             self.paginate_by = self.request.GET.get('shoespp', 2)

        context = super().get_context_data(**kwargs)

        return context


另请参见问题How do I use pagination with Django class based generic ListViews?第二个答案中的代码

相关问题 更多 >

    热门问题