2016-01-23 31 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