0

Let's say I have a ListView that looks like this:

class CarsListView(ListView):
    model = Car
    paginate_by = 5

and a model Car:

class Car(models.Model):
    created = models.DateTimeField()
    brand = models.CharField(max_length=30)

    class Meta:
       ordering = ("created",)

The CarsListView is working correctly showing me all cars ordered by created. So far, so good.

Instead of creating a DetailView for each car, I want to add a view that redirects incoming requests for a specific car to the CarsListView on the correct page.

class CarsRedirectView(RedirectView):
   def get_redirect_url(self, *args, **kwargs):
       car = Car.objects.get(pk=kwargs["pk"])
       # stuck here
       return "hmm?"

All I really need to know here is on which page the car is. One way to do this is to fetch all Car objects and count the pages until I hit the car.

Is there a better way?

Johnny
  • 133
  • 1
  • 2
  • 13
  • You want to go from `ListView` to `DetailView` of the car, am I right? – Zagorodniy Olexiy Nov 24 '16 at 12:21
  • I don't understand what you're asking... are you looking to find what page a particular object is on in a paginated list? – Sayse Nov 24 '16 at 15:18
  • @Sayse yup. Currently I'm counting how many items are before the object and divide that by `paginate_by` to get the page number where the object is. – Johnny Nov 24 '16 at 15:21
  • That would be correct - Here is a [duplicate question](http://stackoverflow.com/q/4429331/1324033) – Sayse Nov 24 '16 at 15:22

1 Answers1

0

One way to this would be:- 1) Make your car url dynamic (use regular expressions to pass id of the car as an argument to the view.)

url(r'^car/(?P<car_id>[0-9]+)/$', 'your_app.views.car_detail', name='detail'),

2) Handle the view like this:-

def car_detail(request, car_id):
    car = Car.objects.get(pk=car_id)

Here you may use the context to pass car object to your template for showing up details:-

    context = {"car":car}
    return render(request, "details.html", context)

3) Now in your template "details.html" you can access it or its properties in this way

<h1>Car Details</h1>
<h3>{{ car.property }}</h3>
Shashishekhar Hasabnis
  • 1,636
  • 1
  • 15
  • 36