嗨,我是一名平面设计师,在编程方面非常新,我已经学习了一段时间的Python,想和Django一起尝试一下,我正在用Django制作我的网站,只是为了好玩和练习而且我制作了这张图片画廊遵循一些教程,但我想为图像添加分类,所以在我的网站上我可以通过分类调用一些图像,而不是一次显示所有图像。我怎么能这样做?
MODELS.PY
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Photo(models.Model):
title = models.CharField(max_length = 200)
width = models.IntegerField(default = 0)
height = models.IntegerField(default = 0)
image = models.ImageField(null= False, blank = False, width_field="width", height_field="height")
timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
def __unicode__(self):
return self.title
class Meta:
ordering = ["-timestamp"]
VIEWS.PY
from django.shortcuts import render, redirect
from django.http import HttpResponse
from apps.photos.models import Photo
# Create your views here.
def photo_list(request):
queryset = Photo.objects.all()
context = {
"photos": queryset,
}
return render(request, 'photos/photos.html', context)
PHOTOS.HTML
{% extends 'base/base.html' %}
{% block contenido %}
<br>
<br>
{% for photo in photos %}
<h1>{{ photo.title }}</h1>
{% if photo.image %}
<img src="{{ photo.image.url }}" class="img-responsive">
{% endif %}
{% endfor %}
{% endblock %}
答案 0 :(得分:0)
在模型中,您可以添加另一个名为
的字段CHOICES = (
#('what_database_save', 'WHAT USER SEE'),
('cat1', 'category'),
('cat2', 'category2'),
)
category = models.Charfield(max_length, choices=CHOICES)
如果您愿意,可以添加选项,然后在表单中使用它。在您的视图中,您可以使用queryset = Photo.objects.filter(category="cat1")
方法