I need to export to csv users of my database, so I have this more or less clear (https://docs.djangoproject.com/en/dev/howto/outputting-csv/), but what I need is to select which fields are exported previously.
Is it possible, using the model, show that you can select which fields will be exported?
The best solution to your question is to create an action in your user admin. Here is how to do it: go to your admin.py and do this
from django.contrib.auth import get_user_model
from django.http import HttpResponse
import csv, datetime
User = get_user_model()
def export_to_csv(modeladmin, request, queryset):
opts = modeladmin.model._meta
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;' 'filename={}.csv'.format(opts.verbose_name)
writer = csv.writer(response)
fields = [field for field in opts.get_fields() if not field.many_to_many and not field.one_to_many]
# Write a first row with header information
writer.writerow([field.verbose_name for field in fields])
# Write data rows
for obj in queryset:
data_row = []
for field in fields:
value = getattr(obj, field.name)
if isinstance(value, datetime.datetime):
value = value.strftime('%d/%m/%Y')
data_row.append(value)
writer.writerow(data_row)
return response
export_to_csv.short_description = 'Export to CSV' #short description
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
'''
Registers the action in your model admin
'''
actions = [export_to_csv]
With this you will be able to select the specific users that you want to export their data and export it at once.
From the console, you could simply try
>>> from django.contrib.auth.models import User
>>> with open('myfile.csv', 'w') as csv:
... for user in User.objects.all():
... d = '%s, %s, %s,\n' % (user.username, user.last_name, user.first_name)
... csv.write(d)
where set d to be whichever fields you want to save.
Of course, this will be a pain if you want to do this several times - it's probably a much better idea to create a custom admin command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With