Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass a context through django's rest_framework
    primarykey
    data
    text
    <p>I'm trying to create a view that returns a regular html-response if not otherwise specified. I'm using django's rest_framework to return a JSON if requested.</p> <p>All works just fine except the part where I want to access my context inside the template.</p> <p>Here's little code example, based on pictures:</p> <pre><code>@api_view(('GET', )) @renderer_classes((TemplateHTMLRenderer, UnicodeJSONRenderer, JSONRenderer, BrowsableAPIRenderer)) def index(request): queryset = Picture.objects.all() page = request.GET.get('page') paginator = Paginator(queryset, 25) try: pictures = paginator.page(page) except PageNotAnInteger: pictures = paginator.page(1) except EmptyPage: pictures = paginator.page(paginator.num_pages) serializer_context = {'request': request, 'pictures': pictures, 'filter': FilterForm()} serializer = PaginatedPictureSerializer(pictures, context=serializer_context) return Response(serializer.data, template_name='index.html') </code></pre> <p>New when I want to access my context inside the template:</p> <pre><code>{% if pictures %} {% for picture in pictures %} ... {% endfor %} {% else %} &lt;p&gt;No pictures are available.&lt;/p&gt; {% endif %} </code></pre> <p>The result is always: No pictures are available (and debuging says the same).</p> <p><strong>EDIT:</strong> as requested</p> <pre><code>class PictureSerializer(serializers.ModelSerializer): class Meta: model = Picture class PaginatedPictureSerializer(pagination.PaginationSerializer): class Meta: object_serializer_class = PictureSerializer </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload