Im trying to access the detailpage of a photo instance, but I can't seem to get it to work. (The category detail page works great!)
I would like to access http//domain.com/main-category/sub-cat/sub-sub-cat/photo-slug/
Models.py:
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
name = models.CharField('category name', max_length=32)
parent = TreeForeignKey('self', null=True, blank=True, verbose_name='parent category', related_name='categories')
slug = models.SlugField(unique=True)
def get_absolute_url(self):
return reverse('gallery', kwargs={'path': self.get_path()})
class Photo(models.Model):
name = models.CharField('photo name', max_length=32)
parent = TreeForeignKey(Category, verbose_name='parent category', related_name='photos')
slug = models.SlugField()
class Meta:
unique_together = ('slug', 'parent')
urls.py:
url(r'^(?P<path>.*)', mptt_urls.view(model='gallery.models.Category', view='gallery.views.category', slug_field='slug'), name='gallery'),
views.py:
def category(request, path, instance):
return render(
request,
'gallery/category.html',
{
'instance': instance,
'children': instance.get_children() if instance else Category.objects.root_nodes(),
}
)
How is it possible to access the photo model using mtpp-urls ?
Edit 1:
Sorry, when I try a url like http//domain.com/main-category/sub-cat/sub-sub-cat/photo-slug
The template display the Gallery main page
because there is no instance
when I try the url with the photo-slug (and yes, the photo has the category as a parent :)
Here is the category.html template:
<html>
<head>
<title>{% if instance %}{{ instance.name }}{% else %}Gallery main page{% endif %}</title>
</head>
<body>
<h3>{% if instance %}{{ instance.name }}{% else %}Gallery main page{% endif %}</h3>
<a href="{% url 'gallery' path='' %}">Gallery main page</a>
{% for ancestor in instance.get_ancestors %}
> <a href="{{ ancestor.get_absolute_url }}">{{ ancestor.name }}</a>
{% endfor %}
> <strong>{{ instance.name }}</strong>
<h4>Subcategories:</h4>
<ul>
{% for child in children %}
<li><a href="{{ child.get_absolute_url }}">{{ child.name }}</a></li>
{% empty %}
<li>No items</li>
{% endfor %}
</ul>
<h4>Photos:</h4>
<ul>
{% for object in instance.photos.all %}
<li><a href="{{ object.slug }}">{{ object.name }}</a></li>
{% empty %}
<li>No items</li>
{% endfor %}
</ul>
</body>
</html>