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.
- Use
ListView
to load all theCat
instances - Render cat instances with a link to the
DetailView
usingget_absoulte_url
- Use
DetailView
to render an individualCat
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>
- [Answered ]-Django: CSS and Images (Static Files) loaded successfully but not applied
- [Answered ]-ImproperlyConfigured url
- [Answered ]-Django not showing updated data from database
- [Answered ]-URL patterns for GET
- [Answered ]-Django allauth – How to know if user is logged in with socialaccount or account?
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'),
- [Answered ]-How in Django upload Photo based on Gallery name from other model field?
- [Answered ]-DJANGO_SETTINGS_MODULE undefined