Rajeev
Rajeev

Reputation: 46899

Sending an object with request

In the below code i am trying to send a object with the request,Is this correct if so how to decode it in template

 def index(request):
      cat = Category.objects.filter(title="ASD")
      dict = {'cat' : cat}
       request.update('dict' : dict) 
          #or
       request.dict=dict;

And In the templates can we write the code as

     {% for obj in request.dict%}
          obj.title
     {% endfor %}

EDIT: If i am calling function like

      def post_list(request, page=0, paginate_by=20, **kwargs):
        logging.debug("post_list")
        page_size = getattr(settings,'BLOG_PAGESIZE', paginate_by)
        return list_detail.object_list(
        request,
        queryset=Post.objects.published(),
        paginate_by=page_size,
        page=page,
        **kwargs
      )

Upvotes: 0

Views: 189

Answers (2)

arie
arie

Reputation: 18972

You're not showing the actual function you use to render your view (render(), render_to_response(), etc.).

Let's say you are using render_to_response() :

render_to_response(template_name[, dictionary][, context_instance][, mimetype])

Renders a given template with a given context dictionary and returns an HttpResponse object with that rendered text.

So if you pass in {"foo": your_object} as a dictionary you can use {{ foo }} directly in your template.


If you are using the object_list generic view you should use the extra_context:

extra_context: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it just before rendering the template.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599450

You could do this, but why would you want to? Django has a simple, well-defined and well-documented way of passing data into templates - through the context. Why try and find ways to work around that?

Edit after comment No. Again, Django has a perfectly good way of passing extra context into a generic view, via the extra_context parameter which again is well-documented.

Upvotes: 2

Related Questions