Reputation: 109
Sorry for asking such a simple question, but I got stuck on (as I think) this trivial problem. I have a simple gallery model in Django and want to get a category list for photos. My model looks like this:
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
And the choices.py
file looks like this:
CATEGORIES = (
(1, ('Mountains')),
(2, ('Animals')),
(3, ('Macro')),
(4, ('People'))
)
What I'm looking for is getting a list like this:
Mountains | Animals | Macro | People
in my templates.
Upvotes: 1
Views: 147
Reputation: 8400
You need to create model form for this,
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>
What I'm looking for is getting a list like this:
Mountains | Animals | Macro | People
Create New form like,
class PhotosForm(forms.Form):
category = forms.ChoiceField(choices=CATEGORIES)
Add view to 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)
And at last you need to add template,
{% if photos %}
<display pics>
{% else %}
{% for key, value in categories %}
<a href='showpics?id={{key}}'>{{value}}</a>
{% endfor %}
And last showpics
should be point to show_list
Upvotes: 3