[Answer]-Get single record from database Django

0đź‘Ť

âś…

Where’d you get get_record() from? The return value of get_object_or_404 is a model instance. There’s nothing else to “get”, just pass the instance to your context. And, don’t use object_list as a context name. Not only is this an instance, not a list or queryset, but that name is most often used with pagination, and you’ll simply create confusion in your code if you’re not actually paginating anything.

return render_to_response('templates/page/page.html', {
    'one_page': one_page,
})

Then in your template:

<h1>{{ one_page.title }}</h1>
<img src="{{ one_page.image.url }}" alt="">
<p>{{ one_page.description }}</p>
👤Chris Pratt

1đź‘Ť

If you would want to query the database for a single Page model you could use

views.py

from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse 
from models import Pages



def page(request, slug):
    try:
        page = Pages.objects.get(slug=slug)
    except ObjectDoesNotExist:
        return HttpResponse(status=404)
    return render(request, 'templates/page/page.html', {'page': page})

Then just use

{{page.title}}

or something like that in your template.

Also, if you want to query and have an iterable list returned intead you coule use

Pages.objects.filter()

instead of

Pages.objects.get()
👤L.hawes

Leave a comment