【问题标题】:HTML Button gets executed before pressedHTML按钮在按下之前被执行
【发布时间】:2019-06-04 19:09:38
【问题描述】:

0

我有一个 html 模板,其中包含一个按钮,当你按下按钮时,它会在 views.py 中执行一个函数,我将列出:

from django.shortcuts import render
from django.http import HttpResponse
import requests
from bs4 import BeautifulSoup


def button(request):

    return render(request, 'home.html')

def output(request):
    def trade_spider(max_pages):
        dat = ''
        page = 1
        while(page <= max_pages):
            search = 'Ipad'
            url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page)
            src = requests.get(url)
            text = src.text
            soup = BeautifulSoup(text, features="html.parser")
            for link in soup.findAll('a', {'class': 's-item__link'}):
                href = link.get('href')
                title = link.string
                if(title == None):
                    title = "Sorry the title was unavailable however you can check the price."
                price = get_item_price(href)
                dat += href + '\n' + title + '\n' + price
                page+=1
                return dat


    def get_item_price(item_url):
        src = requests.get(item_url)
        text = src.text
        soup = BeautifulSoup(text, features="html.parser")
        for item_price in soup.findAll('span', {'class': 'notranslate'}):
                price = item_price.string
                return price

    data = trade_spider(1)
    return render(request, 'home.html',{'data': data})

home.html:

<!DOCTYPE html>
<html>
    <head>
        <title>
            Python button script
        </title>
    </head>
    <body>
        <button>Execute Script</button> <hr>
        {% if data %}

        {{data | safe}}

        {% endif %}

        </body>
</html>

一切正常,但是当我运行页面时,它会显示按钮和我不希望的输出,我希望它在我按下按钮后显示输出。 python 版本是 3.6.0 django=2.1 它在一个使用 pipenv 的 virtualenv 中,这就是我所拥有的所有细节。如果您需要另一个文件的代码,只需注释以防您需要该目录,并且其中的文件是一棵树:

C:.
│   Pipfile
│   Pipfile.lock
│
└───comparison
    │   db.sqlite3
    │   manage.py
    │
    ├───comparison
    │       settings.py
    │       urls.py
    │       wsgi.py
    │       __init__.py
    │
    └───register
        │   admin.py
        │   apps.py
        │   models.py
        │   tests.py
        │   views.py
        │   __init__.py
        │
        ├───migrations
        │       __init__.py
        │
        └───templates
                home.html

views.py:

from django.contrib import admin
from django.urls import path
from register.views import output

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', output)
]

【问题讨论】:

  • 那么你期待什么?您调用该函数,它会显示结果。据我所知,该按钮从未使用过。

标签: html django python-3.x


【解决方案1】:

一个单独的按钮本身不会做任何事情。

要使按钮可点击,请将按钮包装在 &lt;form&gt; 元素中,并为表单提供 action 以及您要将表单提交发送到的页面。也给它methodpost。还要为按钮提供submit 的type 和一个值。像这样的:

<form name="myform" method="post" action="/register/">
  <button type="submit" value="execute">Execute Script</button>
</form>

然后在您的 Django 视图中,您仅在单击按钮时才打印输出。 您可以通过查看请求方法是否为 post 以及提交按钮是否已提交来检查。

类似这样的:


def output(request):

    data = False #Setting the default to false makes it easy to check for it in your template.
    submitbutton= request.POST.get('execute') #Looking for the value of the button in the POST variables.

    if submitbutton:
    # Only if the button has been clicked, do we execute the code to get the output.
        def trade_spider(max_pages):
            dat = ''
            page = 1
            while(page <= max_pages):
                search = 'Ipad'
                url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page)
                src = requests.get(url)
                text = src.text
                soup = BeautifulSoup(text, features="html.parser")
                for link in soup.findAll('a', {'class': 's-item__link'}):
                    href = link.get('href')
                    title = link.string
                    if(title == None):
                        title = "Sorry the title was unavailable however you can check the price."
                    price = get_item_price(href)
                    dat += href + '\n' + title + '\n' + price
                    page+=1
                    return dat


        def get_item_price(item_url):
            src = requests.get(item_url)
            text = src.text
            soup = BeautifulSoup(text, features="html.parser")
            for item_price in soup.findAll('span', {'class': 'notranslate'}):
                price = item_price.string
                return price

        data = trade_spider(1)
    # We still return the same thing, but unless the button has been clicked, the value of data will remain False
    return render(request, 'home.html',{'data': data})

现在模板中的{% if data %} 只会在按钮被点击时返回True,所以如果没有点击它就不会尝试显示任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    相关资源
    最近更新 更多