我試圖創建一個函數,可以檢測到每篇文章的圖像的顏色,但我很難使其正常工作。Django圖像顏色檢測功能不叫
這裏是我的代碼
views.py
from collections import defaultdict
from PIL import Image
def article(request):
context = {'article': Article.objects.all()}
return render(request, 'article.html', context)
def color_detection(request):
article = get_object_or_404(Article, None)
image = article.image
my_image = Image.open(image)
by_color = defaultdict(int)
for pixel in my_image.getdata():
by_color[pixel] += 1
total = 0
for key, x in by_color.items(): #taking the elements of dict
a = [i for i in key] #turning them into multiple lists
if total <= 1: #taking the first list of the list of lists
tuple_of_a = tuple(a)
print(tuple_of_a) #should return the color of one colored pixel of the image something like (r, g, b)
context = {'color':tuple_of_a}
total += 1
else:
break
return render(request, 'article.html', context)
[... other unrelated views ...]
urls.py
urlpatterns = [
url(r'^$', views.article, name="index"),
url(r'^$', views.color_detection, name='color_detection'),
[... unrelated urls ...]
]
template.py
{% for a in article %}
[... unrelated html ...]
<p>{{ a.color }}</p>
{% endfor %}
這是我在django作爲初學者的第一個項目,所以我的錯誤可能是基本的,但我不明白爲什麼不調用color_detection()函數,如果你看到代碼中的其他錯誤,指出,它會非常有幫助。
有什麼想法/建議嗎?
謝謝你,我很困惑意見和模型。沒有理解我的操作在哪裏。 – Lindow