Кнопка HTML выполняется перед нажатием - PullRequest
0 голосов
/ 04 июня 2019

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, она в virtualenv использует pipenv и это все, что у меня есть. Если вам нужен код другого файла, просто прокомментируйте также, если вам нужен каталог, а файлы в нем - это дерево:

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)
]

1 Ответ

0 голосов
/ 05 июня 2019

Одинокая кнопка сама по себе ничего не сделает.

Чтобы сделать кнопку кликабельной, вы оборачиваете кнопку внутри элемента <form> и даете форме action с нужной страницей.отправить форму отправки на.Также дайте ему method post.Также дайте кнопке type из submit и значение.Примерно так:

<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 только если кнопка была нажата, поэтому она не будет пытаться отобразить что-либо, если это не так.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...