Model:
class Car(models.Model):
name = models.CharField(max_length=10, unique=True)
def __unicode__(self):
return self.name
def get_absolute_url(self):
return reverse('cars.views.car', args=[str(self.id)])
View:
def car(request):
all_cars = Car.objects.all().filter(active=1).values('id', 'name')
return render(request, 'car.html', {'all_cars': all_cars})
URL mapping:
url(r'^car/$', 'cars.views.car'),
in car.html, I’m using:
<li><a href="{{ car.get_absolute_url }}">{{ car.name }}</a></li>
But it didn’t print /car/N/, only /car/. How to fix it? With this (<!-- BAD template code. Avoid! -->) it works, but dont works with get_absolute_url.
Your URL pattern doesn’t accept any argument, so django can’t generate an URL with the argument!
Should be:
But then your
carview wouldn’t work, because it looks like it gives a listing of cars.You probably want two URLS: one for a car listing, and one for a specific car. They’ll need to map to two different views:
On a sidenote, you should look into generic views, they would make this entire process simpler.