[Answered ]-Create views of model instances in Django

2👍

✅

Django has built in views to do exactly what you are trying to do!

Combining ListView and DetailView should fulfill your requirements. The documentation links provide urlconf examples.

You can use ListView to get all the Cat instances in your system, and render them. Django has a convention of using an model instance method called get_absolute_url to get the link to view an individual instance. That link should point to the DetailView you set up to render Cat instances.

  1. Use ListView to load all the Cat instances
  2. Render cat instances with a link to the DetailView using get_absoulte_url
  3. Use DetailView to render an individual Cat instance.

The important thing is, django provides all the tools (in the form of ClassBasedViews) to accomplish what you outlined in your question

0👍

You can use models.permalink to define the object’s url.

from django.db import models

class Cat(models.Model):
    name = models.CharField(max_length=32)

    @models.permalink
    def get_absolute_url(self):
        return ('cats_detail', [self.pk])

You can then use generic views and create the “cat_detail” named url.

https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-display/

In the template: <a href="{{ object.get_absolute_url }}">{{ object.name }}</a>

0👍

I will give an example of how I usualy do this. For example, I could use the cat’s name as a slug for my url addresses.

See if it could help:

#models.py
from django import models
from django.template.defaultfilters import slugify
from django.db.models import signals
from django.core.urlresolvers import reverse

class Cat(models.Model):
    name = models.CharField(max_length = 200)
    slug = models.SlugField(blank=True,null=True)
    def get_absolute_url(self):
        return reverse('see-cat',
        kwargs=(
        {'slug':self.slug})

    )

#Signals
def slug_pre_save(signal, instance, sender, **kwargs):
    """
    This is a pre-save signal. It will put a value into slugify before it is saved on the model.
    """
    if not instance.slug:

        slug = slugify(instance.name)
        new_slug = slug
        cont = 0

        while sender.objects.filter(slug=new_slug).exclude(id=instance.id).count() > 0:
            cont +=1
            new_slug = '%s-%d' % (slug,cont)

        instance.slug = new_slug

#Now I gonna connect the signal and the Cat Class
signals.pre_save.connect(slug_pre_save, sender=Cat)

#urls.py
url(r'^see-cat/(?P<slug>[\w_-]+)/$',
        'your_see_cat_view',name='see-cat'),

Leave a comment