Django:点击图片并在新页面中打开它

时间:2015-03-20 16:21:25

标签: django image hyperlink

django和python的新手,请以非常简单的方式向我提出建议。

基本上我有一个图像托管网站,我希望能够点击任何图像并让它打开一个显示图像的新页面。我该怎么做呢?我认为我必须得到图像网址,但我不知道如何。这也必须是自动的。

型号:

class UploadImages(models.Model):

    category_choice=(('Full','Full Beard'),
                ('tashe', 'Moustache'),
                ('goat','Goatee'))

    image = models.ImageField(upload_to='rate', blank=True)
    name =  models.CharField(max_length=128, default=0)
    user = models.ForeignKey(User)
    date = models.DateTimeField(default=now())
    #category = models.ForeignKey(Categories)
    category = models.CharField(max_length=30, choices=category_choice)
    rating = models.IntegerField(default=0)

    def __unicode__(self):
        return self.name

查看:

def index(request):

    if request.method == 'GET':

        #images_list = UploadImages.objects.order_by('-date')
        images_list = UploadImages.objects.filter(category='tashe')
        category_list = Category.objects.order_by('-likes')[:5]
        page_list = Page.objects.order_by('-views')[:5]

        context_dict = {'images':images_list}
        response = render(request,'RateMyBeard/index.html', context_dict)
        return response

    else:
        rating = request.POST['submit']
        #images_list = UploadImages.objects.order_by('-date')
        images_list = UploadImages.objects.filter(category='tashe')
        print rating
        #print images_list

        return render(request, 'RateMyBeard/index.html', images_list)

HTML

{% extends 'base.html' %}

{% load staticfiles %} <!-- New line -->



{% block body_block %}

<p> 'check our images'</p>

             {% for image in images %}
                 <a href="upload/">
                 <img src="{{image.image.url}}" alt="{{image.name}}" >
                    </a>

              {% endfor %}

  {% csrf_token %}
{% endblock %}

1 个答案:

答案 0 :(得分:5)

target="_blank"属性添加到<a>标记,链接将在新窗口/标签中打开:

<a href="{{image.image.url}}" target="_blank">
    <img src="{{image.image.url}}" alt="{{image.name}}">
</a>