Django 1.11实现Admin后台Auto模型数据导出CSV功能求助
Got it, let's get your CSV export button working in Django 1.11's admin backend step by step. I'll fix your existing code and show you the proper way to add this feature:
Step 1: Fix Your Auto Model First
Your model has a couple of issues that need addressing before we proceed:
CharFieldrequires amax_lengthparameter (missing forTeamandScout)- Duplicate key values in the
nwchoices (two entries with1) IntegerFielddefaults should match the choice keys, not the labels
Here's the corrected model:
from django.db import models class Auto(models.Model): YNC = (('N', 'No'), ('Y', 'Yes'), ) NYC = (('N', 'No'), ('Y', 'Yes'), ) NNY = (('N', 'No'), ('Y', 'Yes'), ) nw = ( (1, 'Really Bad'), (2, 'Bad'), # Fixed duplicate key (3, 'Average'), (4, 'Good'), (5, 'Really Good'), ) Team = models.CharField(max_length=100) # Added max_length Scout = models.CharField(max_length=100) # Added max_length StartWithCubeLoaded = models.CharField(max_length=1, choices=YNC, default='N') CrossAutoLine = models.CharField(max_length=1, choices=YNC, default='N') RobotCrossCenterLine = models.CharField(max_length=1, choices=YNC, default='N') PlaceCubeInWrongScale = models.CharField(max_length=1, choices=YNC, default='N') RobotHitOtherAllianceRobotInNullZone = models.CharField(max_length=1, choices=YNC, default='N') MisPlaceCube = models.CharField(max_length=1, choices=YNC, default='N') DroppedCubes = models.IntegerField(default=0) DoubleStackScale = models.CharField(max_length=1, choices=NYC, default='N') Foul = models.CharField(max_length=1, choices=NYC, default='N') KnockedOffCubes = models.IntegerField(default=0) MissedCubes = models.IntegerField(default=0) Climbed = models.CharField(max_length=1, choices=NNY, default='N') ClimbTime = models.IntegerField(default=0) Lifted2Robots = models.CharField(max_length=1, choices=NNY, default='N') ProvidedBar = models.CharField(max_length=1, choices=NNY, default='N') ProvidedRamp = models.CharField(max_length=1, choices=NNY, default='N') GrabFieldBar = models.CharField(max_length=1, choices=NNY, default='N') ClimbAttempted = models.CharField(max_length=1, choices=NNY, default='N') GrabRobotBar = models.CharField(max_length=1, choices=NNY, default='N') ClimbRobotRamp = models.CharField(max_length=1, choices=NNY, default='N') NoShow = models.CharField(max_length=1, choices=NNY, default='N') TippedOver = models.CharField(max_length=1, choices=NNY, default='N') Broke = models.CharField(max_length=1, choices=NNY, default='N') TeamWork = models.IntegerField(choices=nw, default=1) # Default uses key, not label PickingUpCubes = models.IntegerField(choices=nw, default=1) Driving = models.IntegerField(choices=nw, default=1) PlacingCubes = models.IntegerField(choices=nw, default=1) def __str__(self): return f"Auto Record - Team {self.Team}"
Step 2: Add CSV Export Action to Admin
The cleanest way to add a download button in Django Admin is using custom actions. Create/modify your admin.py file:
from django.contrib import admin from django.http import HttpResponse import csv from .models import Auto def export_auto_to_csv(modeladmin, request, queryset): # Configure CSV response headers response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="auto_records.csv"' writer = csv.writer(response) # Get all field names for CSV headers field_names = [field.name for field in Auto._meta.fields] writer.writerow(field_names) # Write each record to CSV, converting choice values to human-readable text for obj in queryset: row = [] for field_name in field_names: value = getattr(obj, field_name) field = Auto._meta.get_field(field_name) # Convert stored choice keys to their display labels if field.choices: value = dict(field.choices).get(value, value) row.append(str(value)) writer.writerow(row) return response # Set the name that appears in the Admin action dropdown export_auto_to_csv.short_description = "Export selected Auto records to CSV" class AutoAdmin(admin.ModelAdmin): # Optional: Customize fields shown in the Admin list view list_display = ('Team', 'Scout', 'CrossAutoLine', 'Climbed') # Add our export action to the Admin actions = [export_auto_to_csv] # Register the model with our custom Admin class admin.site.register(Auto, AutoAdmin)
Step 3: Fix URL Conflicts
Your original urls.py had two views mapped to the same root URL (r'^$'), which would break functionality. Here's the corrected version:
from django.conf.urls import url from django.contrib import admin from system.views import index urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index), # If you still want a standalone export page, uncomment this (use a unique path): # url(r'^export-auto-csv/$', dcsv), ]
Step 4: Update Your View (Optional)
If you want to keep the standalone export view, fix the dcsv function in views.py to handle all fields properly:
from django.shortcuts import render from django.http import HttpResponse from .models import Auto from .forms import AutoForm import csv def index(request): form = AutoForm() if request.method == "POST": form = AutoForm(request.POST) if form.is_valid(): form.save() # Add success handling here if needed return render(request, 'index.html', {'form': form}) def dcsv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="auto_records.csv"' writer = csv.writer(response) field_names = [field.name for field in Auto._meta.fields] writer.writerow(field_names) for obj in Auto.objects.all(): row = [] for field_name in field_names: value = getattr(obj, field_name) field = Auto._meta.get_field(field_name) if field.choices: value = dict(field.choices).get(value, value) row.append(str(value)) writer.writerow(row) return response
How to Use It
- Run migrations to apply model changes:
python manage.py makemigrations python manage.py migrate - Restart your Django server.
- Go to the Admin backend, navigate to the Auto model page:
- Select the records you want to export (or use "Select all" checkbox)
- Choose "Export selected Auto records to CSV" from the action dropdown
- Click the "Go" button, and your CSV file will download automatically
内容的提问来源于stack exchange,提问作者nwf
相关产品推荐
相关产品推荐

