Issues Importing CSV Data in Django Custom Management Command (DictReader Parsing Error)

Hi everyone,

I'm working on a Django project where I need to import questions from a CSV file into my database using a custom management command. However, I'm facing an issue with parsing the CSV rows.

Here’s what I’m doing:

I’m using csv.DictReader to read the CSV file. My CSV file includes columns like subject, topic, difficulty_level, text, options, correct_option, and image. Here’s a sample of my CSV:

subject,topic,difficulty_level,text,options,correct_option,image Physics,Thermodynamics,2,"Calculate ( W = P \cdot \Delta V ) for ( P = 100 , kPa ).","{""A"":""100 J"",""B"":""200 J"",""C"":""300 J"",""D"":""400 J""}","A","question_images/thermo_diagram.png" Math,Calculus,3,"Evaluate ( \int_0^1 x^2 dx ).","{""A"":""1/2"",""B"":""1/3"",""C"":""1/4"",""D"":""1/5""}","B",""

Here’s the issue I’m encountering:

When I run my management command, DictReader doesn’t seem to parse the rows correctly. I get errors like:

javascript Copy code Error importing question: Unknown - 'subject' Debugging shows that the entire row is being read as a single key-value pair, rather than splitting into individual fields.

I’ve tried:

Ensuring the CSV file is UTF-8 encoded. Adding debugging to confirm the raw content of the CSV. Here’s my current code snippet for reading the CSV:

python Copy code with open(csv_file, newline='', encoding='utf-8-sig') as file: reader = csv.DictReader(file) for row in reader: print("Parsed Row:", row) # Debugging What could be causing DictReader to treat the entire row as one key-value pair? How can I properly parse the CSV into fields like subject, topic, etc.?

Any help would be greatly appreciated!

should do the work =)

was testing on your example

with open(csv_file, "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)
Вернуться на верх