views:

38

answers:

1

I have a view that displays object information when the correct URL is provided however I would like to create a similar view that returns url information from the record that is located next.

So in essence take the info from my first view, list/order it in some way preferably by date and return the records located next and previous in the list.

Can somebody please explain to me and provide a simple example of how I would do this. I am new to django and I am stuck. All Help is greatly appreciated. Thanks.

Here are the models URLs and views I have used

Model

class Body(models.Model):
    type = models.ForeignKey(Content)
    url = models.SlugField(unique=True, help_text='')
    published = models.DateTimeField(default=datetime.now)
    maintxt = models.CharField(max_length=200)

View

def news_view(request, url):
    news = get_object_or_404(Body, url=url)
    next = news.get_next_by_published().get_absolute_url()
    return render_to_response('news/news_view.html', {
        'news': news,
        'next': next
    }, context_instance=RequestContext(request))

URL

url(r'^/(?P<url>[\w\-]+)/$', 'news_view', name="news_view"),

Template

<a href="{{ next.get_absolute_url }}">Next</a></p>
+1  A: 

add get_absolute_url to your model

class Body:
    #[....]
    def get_absolute_url(self):
        return "/%i/" % self.url # but please rename it to slug

get the next url in the view (with get_next_by_FOO)

def news_view(request, url):
    #[....]
    try
        next_url = news.get_next_by_published().get_absolute_url()
    except Body.DoesNotExist
        next_url = None
    return #[....] and include next_url

use this next_url in your template

{% if next_url %}
<a href="{{next_url}}">next</a>
{% endif %}
Andre Bossard
How would you limit the view so it does not raise a query that doesn't exist and subsequently raise an error?
Rick
Actually I don't understand your comment. But I think the answer is: "try .... except Body.DoesNotExist" and there you set next_url to None. And in the Template you check if its set.
Andre Bossard
Maybe you can even do everything just in the template....
Andre Bossard