title: Django Pagination - Redirecting to the page an object is on
body: <p>I'm working on an image portfolio app, and I've got a url which looks like this:</p>
  
  <pre><code>url(r'^(?P&lt;slug_val&gt;[-\w]+)/(?P&lt;page&gt;[0-9]+)/(?P&lt;id&gt;[0-9]+)/$', 'portfolio.views.imagedetail')
  </code></pre>
  
  <p>Essentially, the <code>page</code> element is only there so I can nicely redirect the user back to the page of thumbnails they came from. However, if the URL gets passed around, and then some images get added or removed before the image, then it may no longer be on that page. I'd like to redirect users in that case to:</p>
  
  <pre><code>slug/correctpage/id
  </code></pre>
  
  <p>What I can't work out is how to work out what page an image is on, using Django's built-in pagination. Here's what I've got so far:</p>
  
  <pre><code>def imagedetail(request, slug_val, page, id):
      p = get_object_or_404(MyPortfolio, slug=slug_val)
  
      paginator = Paginator(p.images.all(), 25)
  
      # find out which page the image with id is on, if it's not page,
      # then redirect, otherwise render
  </code></pre>
  
  <p>I know I could iterate through each page, but that seems like it'll hit the database unnecessarily, and I'm sure there must be a more elegant way to do it.</p>
  
  <p>Thanks,</p>
  
  <p>Dom</p>