2016-01-23 28 views
0

我試圖創建一個函數,可以檢測到每篇文章的圖像的顏色,但我很難使其正常工作。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()函數,如果你看到代碼中的其他錯誤,指出,它會非常有幫助。

有什麼想法/建議嗎?

回答

1

它會被稱爲?您只能有一個視圖響應請求,並且該URL已被您的索引視圖捕獲。即使它被稱爲,它將在哪個文章上運行?你期望get_object_or_404(Article,None)做什麼?

看來你對什麼觀點感到困惑;他們響應請求,並且只有一個視圖可以映射到特定的URL。但實際上,這根本不是一種觀點;這實際上是一個實用功能,您可以調用特定的文章對象。所以,它應該是一個方法上的文章模型;然後,它運行在一個已經爲self傳遞的文章,並返回一些數據,而不是試圖呈現一個模板:

class Article(models.Model): 
    ... fields and Meta ... 

    def color_detection(self): 
     image = self.image 
     ... 
     return tuple_of_a 

現在你的模板可以這樣做:

{% for a in article %} 
    [... unrelated html ...] 
    <p>{{ a.color_detection }}</p> 
{% endfor %} 
+0

謝謝你,我很困惑意見和模型。沒有理解我的操作在哪裏。 – Lindow

0

您尚未爲其指定特定的網址,「index」和「color_detection」都映射到根(r'^$')。 Django會調用第一個匹配url模式的視圖,在你的案例views.article