frlan
frlan

Reputation: 7260

Django: Is it possible to direct access objects from database inside a template

Is there any way to get a list of objects of one class without creating a dedicated view just using maybe TemplateView.as_view() and a template?

Upvotes: 0

Views: 237

Answers (2)

nnmware
nnmware

Reputation: 950

Sure. You can use assignment tag(write this in template tag library). Assignment tag docs

@register.assignment_tag
def my_tag():
    return Product.objects.all()

In template(TemplateView - no problem)

{% my_tag as my_tag %}
{% for item in my_tag %}
    {{ item.name }}
{% endfor %}

Upvotes: 1

coldmind
coldmind

Reputation: 5417

In fact, you need something, that will be returning a response object. That is what view actually is.

If you don't want to declare view as function or class, you can use lambda-functions. Here is example of working urls.py:

from django.conf.urls import url
from django.contrib.auth.models import User

from django.shortcuts import render_to_response



urlpatterns = [
        url(r'^test/$', lambda request: render_to_response('testapp/test.html', {'users': User.objects.filter()})),
]

I created anonymous function and returned response with objects I need and specified path to template.

Upvotes: 1

Related Questions