SheepDogInc/sheepdog_tables — pull request #21 by thurloat (2013-11-22 15:56:09+00:00)
Title: Implement the csv functionality as an extension of a regular view.

Define one class, get as_view and as_csv class methods to register in your urls to pick up on your existing queryset generation and view work done in dispatch so that you don't have to create a second view in order to export your table as a CSV.

Example:

### urls.py
```python
from django.conf.urls import patterns, url
from app import views as v

urlpatterns = patterns('',
url(r'^report/(?P\d{4})/$', v.ReportView.as_view()),
url(r'^report/(?P\d{4})/csv$', v.ReportView.as_csv(), name='report_csv'),
)
```

### views.py
```python

class ReportView(TablesMixin, ListView):
model = models.ExampleModel
main_table = tables.ReportTable()
template_name = 'reports/list.html'
propagate_filter_params = True

def dispatch(self, *args, **kwargs):
year = kwargs.get('year')
try:
self.selected_year = datetime.date(int(year), 1, 1)
except ValueError:
raise Http404("Year not recognized.")
return super(ReportView, self).dispatch(request, *args, **kwargs)

def get_queryset(self, *args, **kwargs):
qs = super(ReportView, self).get_queryset(*args, **kwargs)
return qs.filter(date__startswith=self.selected_year.strftime('%Y-'),)
```

### reports/list.html
```html

Export As CSV

{% with tables.main_table as table %}
{% include "tables/table.html" %}
{% endwith %}
```