Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

django convert model to csv

def download_csv(modeladmin, request, queryset):
    if not request.user.is_staff:
        raise PermissionDenied
    opts = queryset.model._meta
    model = queryset.model
    response = HttpResponse(mimetype='text/csv')
    # force download.
    response['Content-Disposition'] = 'attachment;filename=export.csv'
    # the csv writer
    writer = csv.writer(response)
    field_names = [field.name for field in opts.fields]
    # Write a first row with header information
    writer.writerow(field_names)
    # Write data rows
    for obj in queryset:
        writer.writerow([getattr(obj, field) for field in field_names])
    return response
download_csv.short_description = "Download selected as csv"
Comment

django convert model to csv

def myview(request):
    data = download_csv(ModelAdmin, request, Model.objects.all())

    return HttpResponse (data, content_type='text/csv')
Comment

PREVIOUS NEXT
Code Example
Python :: convert plt.show to image to show opencv 
Python :: 2d array python 
Python :: statsmodels fitted values 
Python :: sqlalchemy one to one foreign key 
Python :: pytorch torchaudio torchvision cu113 
Python :: convert decimal to float in python 
Python :: color module python 
Python :: python get website chrome network tab 
Python :: any() and all() 
Python :: how to create multiple file in python using for loop. 
Python :: speech to text 
Python :: insert a new row to numpy array in especific position 
Python :: jacobi iteration method python 
Python :: .size pandas 
Python :: binary tree python 
Python :: python - sending mail 
Python :: normal discord.py codes 
Python :: how to add some thing in python list 
Python :: how to set environment variable in pycharm 
Python :: Finding if 2 consecutive numbers in a list have a sum equal to a given number 
Python :: django get all model fields 
Python :: element tree directory python 
Python :: # check if the file is not empty and get size 
Python :: geopandas with postgis 
Python :: cv2.imshow not working in vscode 
Python :: How determine if a number is even or odd using Modulo Operator 
Python :: how to get last dimension of an array python 
Python :: basic flask api 
Python :: string remove suffix python 
Python :: embed python discord 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =