如何在 Django 的图片库中创建类别

How can I make categories in a image gallery in Django

你好,我是一名平面设计师,在编程方面还是个新手,我学习 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  %}

在您的模型中,您可以添加另一个名为

的字段
CHOICES = (
            #('what_database_save', 'WHAT USER SEE'),
            ('cat1', 'category'),
            ('cat2', 'category2'),
        )
category = models.Charfield(max_length, choices=CHOICES)

如果需要,您可以添加选项并稍后在您的表单中使用它。在您的视图中,您可以使用 queryset = Photo.objects.filter(category="cat1") 方法

按类别过滤照片