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