【问题标题】:Django: Can't get the GET response value - AttributeError: module 'django.http.request' has no attribute 'GET'Django:无法获取 GET 响应值 - AttributeError:模块 'django.http.request' 没有属性 'GET'
【发布时间】:2021-11-27 03:08:32
【问题描述】:

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

根据Django docs,我一直在做的应该可以。我用 request 和 HttpRequest 尝试过,每次我得到一个“无属性”错误。


    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 为我的问题提供解决方案。我想我现在明白出了什么问题。我正在为可能遇到类似问题的任何人提供解决方案代码。

views.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

template_file.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>

【问题讨论】:

  • 总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是截图,不是链接到外部门户)有问题(不是评论)。还有其他有用的信息。
  • 你的分页只有?page=... ,但没有?shoespp=...——你可能需要?page= ...&amp;shoespp=...。此时它应该发送shoespp,只有点击List Shoes
  • request.GET 是一个字典,当请求中没有shoespp 时,您始终可以使用request.GET.get('shoespp', 2) 获取2
  • 谢谢@furas 我已经对我的帖子进行了编辑。问题是当我尝试以“通常”方式获取 GET 数据时出现错误。
  • 重要的是当您单击List Shoes 或链接到下一页/上一页时出现错误。指向下一个/上一个页面的链接没有shoespp,因此您无法在代码中获取它。您必须将&amp;shoespp=... 添加到分页中的每个链接。

标签: python django


【解决方案1】:

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

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

但其他问题可能是此页面使用 &lt;form&gt; 发送 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?的第二个答案中的代码

【讨论】:

    猜你喜欢
    • 2017-01-20
    • 2021-09-13
    • 1970-01-01
    • 2022-07-21
    • 2020-04-01
    • 2020-11-07
    • 2021-07-04
    • 2012-05-11
    • 2021-10-23
    相关资源
    最近更新 更多