You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React前端上传CSV至Django后端后,如何填充Django模型?

Solution: Import CSV Data into Django Model from React Upload

Hey there! You’ve already nailed the frontend file upload part—nice work! Now let’s get that CSV data into your Data model properly. Here’s a step-by-step guide tailored to your code:

1. Fix the Frontend State Initialization

First, a quick fix for your React component: you forgot to initialize the state, which will cause errors when you select a file. Add a constructor to your App class:

// frontend/src/App.js
class App extends Component {
  constructor(props) {
    super(props);
    // Initialize state to hold the uploaded file
    this.state = {
      fileToUpload: null
    };
  }

  // ... rest of your handleFile, handleSubmitData, and render methods stay the same
}

2. Update Django Backend to Process CSV

Modify your views.py to read the CSV content, map rows to your Data model fields, and bulk-insert the records (way more efficient than saving one by one).

First, add necessary imports:

# views.py
import csv
from datetime import datetime
from dateutil.parser import parse  # Install with `pip install python-dateutil` for flexible date parsing
from rest_framework import views
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser, FormParser
from .models import Data

Then update your RegisterData view's post method:

class RegisterData(views.APIView):
    parser_classes = (FormParser, MultiPartParser)

    def post(self, request):
        # Get the uploaded CSV file
        csv_file = request.FILES.get('file')
        
        # Validate file type
        if not csv_file or not csv_file.name.endswith('.csv'):
            return Response({"error": "Please upload a valid CSV file"}, status=400)
        
        try:
            # Read and decode the CSV file
            decoded_content = csv_file.read().decode('utf-8').splitlines()
            reader = csv.DictReader(decoded_content)
            
            # Prepare list of Data objects for bulk creation
            data_records = []
            for row_num, row in enumerate(reader, start=2):  # Start at 2 to account for CSV header
                try:
                    # Map CSV columns to model fields (ensure CSV column names match these keys!)
                    record = Data(
                        city=row.get('city'),
                        wheel_type=row.get('wheel_type'),
                        order_status=row.get('order_status'),
                        order_ID=int(row.get('order_ID', 0)),
                        client_ID=int(row.get('client_ID', 0)),
                        # Use dateutil to auto-parse date formats (adjust if you know your exact format)
                        placed_time=parse(row.get('placed_time')) if row.get('placed_time') else None,
                        order_date_time=parse(row.get('order_date_time')) if row.get('order_date_time') else None,
                        origination_latitude=float(row.get('origination_latitude', 0.0)),
                        origination_longitude=float(row.get('origination_longitude', 0.0)),
                        destination_latitude=float(row.get('destination_latitude', 0.0)),
                        destination_longitude=float(row.get('destination_longitude', 0.0)),
                        surchage_total=float(row.get('surchage_total', 0.0)),
                        transaction_value=float(row.get('transaction_value', 0.0)),
                        total_price=float(row.get('total_price', 0.0))
                    )
                    data_records.append(record)
                except ValueError as e:
                    return Response(
                        {"error": f"Invalid data in row {row_num}: {str(e)}"},
                        status=400
                    )
            
            # Bulk insert all records at once (much faster than saving individually)
            if data_records:
                Data.objects.bulk_create(data_records)
            
            return Response({"success": f"Successfully imported {len(data_records)} records"})
        
        except Exception as e:
            return Response({"error": f"Failed to process CSV: {str(e)}"}, status=500)

3. Key Notes to Avoid Issues

  • CSV Column Matching: Make sure your CSV's column headers exactly match the keys used in row.get('column_name') (e.g., if your CSV has a header "City" instead of "city", update the code to row.get('City')).
  • Date Format: If you know the exact date format in your CSV (e.g., YYYY-MM-DD HH:MM:SS), replace parse() with datetime.strptime(row.get('placed_time'), '%Y-%m-%d %H:%M:%S') for better performance.
  • Data Validation: The code includes basic error handling for invalid data types, but you can add more checks (e.g., ensuring required fields aren't empty) based on your needs.
  • Bulk Creation: Using bulk_create is crucial for performance when importing large CSV files—it minimizes database hits.

4. Test It Out

  1. Make sure you install python-dateutil if you use the flexible date parsing:
    pip install python-dateutil
    
  2. Run your Django server and React app, upload a properly formatted CSV, and check your Django admin to see the imported records!

内容的提问来源于stack exchange,提问作者Roger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:57:51