Day Log App in Django Part 5: Show a DayLog

This post will discuss how to show a Daylog’s details in a page.

Table of Contents

Steps

Create test

The tests will check for a valid slug parameter.

def test_detail_view_with_a_valid_daylog(self):
    daylog = create_daylog()
    response = self.client.get(reverse('daylog:details', args=(daylog.slug,)))

    self.assertEqual(response.context['daylog'], daylog)
    self.assertEqual(response.context['operation'], 'view')

def test_detail_view_with_an_invalid_daylog(self):
    response = self.client.get(reverse('daylog:details', args=('fake-slug',)))

    for message in response.context['messages']:
        self.assertEqual(message.message, "Day Log does not exist.")
        self.assertEqual(message.extra_tags, "danger")
        break;

Set URL

Add the URL to view Daylogs by their slug attribute in api/urls.py. This will be passed to the views.details method.

url(r'^(?P<slug>.+)/$', views.details, name='details'),

Create details method

Add the following method in daylog/views.py:

def details(request, slug):
    try:
        daylog = Daylog.objects.get(slug = slug)
    except Daylog.DoesNotExist:
        messages.error(request, "Day Log does not exist.", "danger")
        return get_list(request)

    return render(request, 'daylog/form.html', {
        'daylog': daylog,
        'operation': 'view'
    })

First the provided slug is fetched from the database. If it does not exist, then it should go back to the mhome page with an error message.

Home page with Daylog DNE alert

The file daylog/form.html is still used, only this time all fields are disabled and the form buttons not available.

View Daylog page

References

Twitter, LinkedIn