Для этого вам нужно создать форму модели,
models.py
CATEGORIES = (
(1, 'Mountains'),
(2, 'Animals'),
(3, 'Macro'),
(4, 'People')
)
class Photo(models.Model):
title = models.CharField(max_length=150)
image = models.ImageField()
description = models.TextField()
category = models.IntegerField(choices=CATEGORIES)
published = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
form.py
from django import forms
from .models import Photo
class PhotoModelForm(forms.ModelForm):
class Meta:
model = Photo
fields = ['__all__']
views.py
from django.shortcuts import render
form .forms import PhotoModelForm
def index(request):
if request.POST:
form = PhotoModelForm(request.POST)
if form.is_valid():
form.save()
else:
form = PhotoModelForm()
return render(request, 'template.html', {'form': form})
template.py:
<form method="POST">
{% csrf_token %}
{{form}}
<input type="submit" value="ok"/>
</form>
Мне нужен список, подобный следующему:
Mountains | Animals | Macro | People
Создать новую форму как,
class PhotosForm(forms.Form):
category = forms.ChoiceField(choices=CATEGORIES)
Добавить представление к views.py
def show_list(request):
context = {}
if request.POST:
form = PhotosForm(request.POST)
if form.is_valid():
photos = Photo.objects.filter(category=form.cleaned_data['category'])
context['photos'] = photos
else:
context['form'] = PhotosForm()
context['categories'] = dict((x, y ) for x, y in CATEGORIES)
return render(request, 'template1.html', context)
И, наконец, вам нужно добавить шаблон,
{% if photos %}
<display pics>
{% else %}
{% for key, value in categories %}
<a href='showpics?id={{key}}'>{{value}}</a>
{% endfor %}
И последний showpics
должен быть точкойдо show_list