Forums

Server error with csv export

Hi, I have a csv export that runs in my view just fine in my development environment, but here I get a server error. There is nothing in the server or the error log. I am using django 1.7 and python 2.7. Here is the code:

def csv_entered(request):
    queryset=Item.objects.filter(event='SilverPaws2015').exclude(aes_item_number__isnull=True)
    #filter(received='Received')
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="aes_entered.csv"'
    writer = csv.writer(response)
    writer.writerow(['ID','Category','ItemName','Donor','AESItemNum','Notes','Date'])
    for item in queryset:
        writer.writerow([item.id,item.category,item.item,item.donor,item.aes_item_number,
            item.notes,item.created_at])
    return response

I don't see anything obvious in that code that could cause an error. It seems strange that there's nothing in the error log? Have you tried enabling debug mode to see the error?

I figured it out...after taking out the fields one by one... there was unicode in my data in pythonanywhere but not on my development side, which is why it only failed here. Someone pasted in data with the "reserved" (R with a circle around it) symbol. I solved it with this:

http://code.activestate.com/recipes/466341-guaranteed-conversion-to-unicode-or-byte-string/

def safe_str(obj):
    """ return the byte string representation of obj """
    try:
        return str(obj)
    except UnicodeEncodeError:
        # obj is unicode
        return unicode(obj).encode('unicode_escape')

I put this function above the csv_entered function and then call it on each string when I write the row...a bit cumbersome but working!

writer.writerow([item.id,item.category,safe_str(item.item),safe_str(item.donor),safe_str(item.aes_item_number), safe_str(item.notes),item.created_at])