ox-it / django-conneg

Content-negotiation for Django
BSD 3-Clause "New" or "Revised" License
6 stars 5 forks source link

Please provide example app hierarchy #7

Open olberger opened 11 years ago

olberger commented 11 years ago

I find it quite hard to create a minimal app using django-conneg.

I think it would be great to have some example app code using it, for instance based on the polls app from the "Writing your first Django app" tutorial.

Thanks in advance.

olberger commented 11 years ago

I'm not sure this is completely correct, but maybe the following example would help :

import json

from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response

from django_conneg.decorators import renderer

from django_conneg.views import ContentNegotiatedView

class IndexView(ContentNegotiatedView):

    @renderer(format='json', mimetypes=('application/json',), name='JSON')
    def render_json(self, request, context, template_name):
        # ...
        return HttpResponse(json.dumps(context), mimetype='application/json')

    @renderer(format="html", mimetypes=('text/html', 'application/xhtml+xml'), priority=1, name='HTML')
    def render_html(self, request, context, template_name):
        # ...
        return render_to_response(self.join_template_name(template_name, 'html'),
                                      context, context_instance=RequestContext(request),
                                      mimetype='text/html')

    def get(self, request):
        context = {
            # Build context here
            'foo': "bar",
        }

        # Call render, passing a template name (without file extension)
        print "in get"
        return self.render(request, context, 'index')

It mixes the HTML and JSON and illustrates how to define the template name.

Hope this helps.