求助:如何用Axios向Django后端POST含多学生对象的表单数据
Hey there! Let's work through this together. You've already got the dynamic field addition and basic POST requests working—great start! The key here is properly structuring your form data to include both the class-level fields and the array of student objects, then sending that structured data correctly via Axios.
Step 1: Ensure Your Form Collects All Student Fields
First, let's fix how you're capturing student data. Instead of just tracking student names, you need to collect all the required student details (stud_fname, inter_lname, class_section) for each dynamic entry. If you're using Ant Design's Form (which it looks like you are), Form.List is perfect for this—it automatically binds each dynamic student's fields to an array in your form values.
Here's how to update your form code:
// Inside your form component <Form.List name="students"> {(fields, { add, remove }) => ( <> {fields.map(({ key, name, ...restField }) => ( <div key={key} style={{ marginBottom: '1rem' }}> <Form.Item {...restField} name={[name, 'stud_fname']} rules={[{ required: true, message: "Don't forget the student's first name!" }]} > <Input placeholder="Student First Name" /> </Form.Item> <Form.Item {...restField} name={[name, 'inter_lname']} rules={[{ required: true, message: "Student last name is required!" }]} > <Input placeholder="Student Last Name" /> </Form.Item> <Form.Item {...restField} name={[name, 'class_section']} rules={[{ required: true, message: "Class section can't be empty!" }]} > <Input placeholder="Class Section" /> </Form.Item> <Button type="danger" onClick={() => remove(name)} style={{ marginLeft: '0.5rem' }}> Remove Student </Button> </div> ))} <Form.Item> <Button type="secondary" onClick={() => add()}> <Icon type="plus" /> Add Student Details </Button> </Form.Item> </> )} </Form.List> // Don't forget your class-level fields <Form.Item name="ClassName" rules={[{ required: true, message: "Class name is required!" }]} > <Input placeholder="Class Name" /> </Form.Item> <Form.Item name="TeacherName" rules={[{ required: true, message: "Teacher name is required!" }]} > <Input placeholder="Teacher Name" /> </Form.Item> <Form.Item name="SchoolNAme" rules={[{ required: true, message: "School name is required!" }]} > <Input placeholder="School Name" /> </Form.Item>
Step 2: Structure and Send the Request with Axios
When you submit the form, the values object from form.validateFields() will already have the exact structure you need: class fields plus a students array of objects. You can send this directly via Axios.
Here's the submit handler:
handleSubmit = () => { this.props.form.validateFields((err, formValues) => { if (!err) { // formValues matches your desired request format exactly! axios.post('/api/your-class-endpoint/', formValues, { headers: { 'Content-Type': 'application/json' } }) .then(res => { console.log('Submission successful!', res.data); // Add your success logic here (e.g., reset form, show notification) }) .catch(err => { console.error('Submission failed:', err); // Handle errors (e.g., show error message) }); } }); };
Step 3: Configure Django Backend to Accept Nested Data
On the Django side, you'll need a nested serializer to handle the students array. Here's how to set that up with Django REST Framework:
Serializers:
from rest_framework import serializers from .models import Class, Student # Adjust these to your actual models class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ['stud_fname', 'inter_lname', 'class_section'] class ClassSerializer(serializers.ModelSerializer): # Use the StudentSerializer with many=True to handle the array students = StudentSerializer(many=True) class Meta: model = Class fields = ['ClassName', 'TeacherName', 'SchoolNAme', 'students'] def create(self, validated_data): # First, extract student data and create the class students_data = validated_data.pop('students') class_instance = Class.objects.create(**validated_data) # Then create each student linked to the new class for student_data in students_data: Student.objects.create(class=class_instance, **student_data) return class_instance
View (for handling the POST):
from rest_framework import generics from .serializers import ClassSerializer class ClassCreateView(generics.CreateAPIView): serializer_class = ClassSerializer
Quick Note on Your Original Code
Your original loop was only pushing studentName into the students array—with the Form.List approach, you don't need that manual loop anymore. The form will automatically build the full students array with all fields for each entry.
This setup should match the request format you provided, and both frontend and backend will handle the nested data correctly.
内容的提问来源于stack exchange,提问作者Sam

