我正在创建一个 django 应用程序并迭代图像列表。我已经研究了几个小时但毫无结果。我到处寻求帮助,但仍然无法修复。我成功地使用 ajax 收到了 POST 请求,当我将其打印到控制台时,图像源就在列表中。但是,在 django 模板中迭代它时,它没有显示。这很有趣,因为当我点击该请求的购买按钮时,它确实出现了。另外,我正在创建一个小书签,单击该小书签会将当前页面的 URL 数据发送到views.py。我正在使用它将图像数据 src 添加到列表中。
base.html(模板)
<body>
{% csrf_token %}
{% load static %}
<script src="{% static 'js/onload.js' %}" type="text/javascript"></script>
<img width='100px' src="https://i.ibb.co/37ybzSD/neom-V1-NTz-Srn-Xvw-unsplash.jpg">
<img src="https://i.giphy.com/media/tsX3YMWYzDPjAARfeg/giphy.webp">
{% load socialaccount %}
<h1>Billionaire Shopping Game</h1>
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }} !</p>
<a href="logout">Logout</a>
{% else %}
<a href="{% provider_login_url 'google' %}">Login with Google</a>
{% endif %}
<a href="javascript:(function() {let script = document.createElement('script'); script.src = '{% static '/js/bookmarklet.js' %}'; document.body.appendChild(script);})();">Bookmarklet</a>
<a href="javascript: (() => {alert('Hello');})();">Helo alert</a>
<img width="100px" src="{% static 'images/heart.png' %}">
<div>
<form method="POST" action="/">
<label for="url_link">Item Link:</label>
<input type="text" id="url_link" name="url_link" required>
<button type="submit">BUY</button>
</form>
<!-- {% for image in images %}
<img src="{{ image }}">
{% endfor %} -->
{% for book in bookimgs %}
<!-- <img src="{{ book }}"> -->
{{ book }}
{% endfor %}
</div>
<p>Hello. This is Hoko Le.</p>
{% block content %}{% endblock content %}
</body>
views.py
def home(request):
images1 = []
images2 = []
if request.method == 'POST':
homeurl = request.POST.get('url_link')
bookurl = request.POST.get('url')
if homeurl != None and homeurl != '':
rh = requests.get(homeurl, headers=HEADERS)
soup = bs(rh.content, "lxml")
images11 = soup.find_all('img',{"src":True})
images2.clear()
for image in images11:
images1.append(image['src'])
elif bookurl != None and bookurl != '':
rb = requests.get(bookurl, headers=HEADERS)
soupb = bs(rb.content, 'lxml')
images22 = soupb.find_all('img',{"src":True})
images2.clear()
for image in images22:
images2.append(image['src'])
print(image['src'])
print('images2 arr ')
print(images2)
else:
pass
else:
pass
return render(request, 'home.html', {'bookimgs': images2})
bookmarklet.js
function initMyBookmarklet() {
(window.myBookmarklet = function() {
// your JavaScript code goes here!
// window.open("/", "popup", "width=500,height=300");
const element = document.getElementsByTagName("p");
element[0].innerHTML = window.location.href;
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
$.ajax({
url: '',
type: 'POST',
data: {
url: window.location.href,
csrfmiddlewaretoken: csrftoken
}
});
})();
}
我不会添加所有代码,因为它太多了。
这些可能是问题的原因:
images1
列表用于存储 homeurl
的图像,而 images2
列表用于存储 bookurl
的图像,但您正在清除它们的 images2
。def home(request):
images1 = []
images2 = []
if request.method == 'POST':
homeurl = request.POST.get('url_link')
bookurl = request.POST.get('url')
if homeurl != None and homeurl != '':
rh = requests.get(homeurl, headers=HEADERS)
soup = bs(rh.content, "lxml")
images11 = soup.find_all('img',{"src":True})
images1.clear() # changed images2 to images1
for image in images11:
images1.append(image['src'])
elif bookurl != None and bookurl != '':
rb = requests.get(bookurl, headers=HEADERS)
soupb = bs(rb.content, 'lxml')
images22 = soupb.find_all('img',{"src":True})
images2.clear()
for image in images22:
images2.append(image['src'])
print(image['src'])
print('images2 arr ')
print(images2)
else:
pass
else:
pass
print(images2) #make sure images 2 has the correct data
return render(request, 'home.html', {'bookimgs': images2})
bookmarklet.js
中,确保 $.ajax
请求中的 URL 在传递到模板之前正确设置为 home`` view is handling the POST request and make sure that image URLs are correctly populate in the
images2``` 列表所在的端点。 function initMyBookmarklet() {
(window.myBookmarklet = function() {
// your JavaScript code goes here!
// window.open("/", "popup", "width=500,height=300");
const element = document.getElementsByTagName("p");
element[0].innerHTML = window.location.href;
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
$.ajax({
url: '/',
type: 'POST',
data: {
url: window.location.href,
csrfmiddlewaretoken: csrftoken
}
});
})();
}