whoisearth
whoisearth

Reputation: 4170

nested if elif in view

I have the following code which is always returning an HttpResponse even if I change the URL to specify the format -

http://myserver/cdxcomposites/?format=xml

What am I doing wrong with my view?

@csrf_exempt
def cdxcomposites_list(request, format=None):
    """
    List all code, or create a new entry.
    """
    if request.method == 'GET':
        cdxcomposites = CDX_composites.objects.all()
        serializer = CDX_compositesSerializer(cdxcomposites, many=True)
        if format == 'csv':
            return CSVresponse(serializer.data)

        elif format == 'json':
            return JSONresponse(serializer.data)        

        elif format == 'xml':
            return XMLresponse(serializer.data)  

        elif format == 'yaml':
            return YAMLresponse(serializer.data)

        else:
            return HttpResponse(serializer.data)

I'm not including the POST as I haven't gotten that far yet.

edit - if I'm reading correctly with my google-fu the problem is that my if and all my elif statements are not validating so I'm thinking the code is correct, I'm just missing out how to get the value into the view. Here's my urls.py

from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = patterns('rds.views',
    url(r'^cdxcomposites/$', 'cdxcomposites_list'),
    url(r'^cdxcomposites/(?P<pk>[0-9]+)/$', 'cdxcomposites_detail'),
)

urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'xml', 'yaml', 'csv'])

Responding to comments seems the format isn't parsing. I changed the last line to

return HttpResponse(format)

and it gives None.

Upvotes: 1

Views: 211

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250991

Since you're using format_suffix_patterns, you need to pass the format type as .xml after the url:

http://myserver/cdxcomposites/.xml

Another option is to set the Accept header when sending the request.

Related docs: Adding optional format suffixes to our URLs

Upvotes: 1

Mike DeSimone
Mike DeSimone

Reputation: 42805

Query parameters are never passed in via the view's argument list. That's for parts of the URL that are extracted in urls.py.

You need to be looking in request.GET for query parameters in the URL:

format = request.GET.get("format", None)
if format == 'csv':
    return CSVresponse(serializer.data)
#etc...

Upvotes: 3

Related Questions