这是我的序列化程序类。我希望与UserSerializer到SnapCapsulesSerializer建立一对多的关系。我允许将SnapCapsule添加到UserSerializer,因此每个用户都可以访问其snapcapsule。这是我在创建关系序列化程序时引用的链接。 http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
snapcapsules = SnapCapsuleSerializer(
many=True,
read_only=True,
allow_null=True,
)
class Meta:
model = User
fields = ('snapcapsules', 'url', 'username', 'email', 'password')
write_only_fields = ('password',)
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, instance, validated_data):
assert (validated_data), "No data recieved."
for capsule in validated_data.get("snapcapsules", []):
snapcapsulea = instance.snapcapsules
snapcapsule = SnapCapsule.object.create(user=instance.username,
**capsule)
snapcapsule.save()
snapcapsules.append(snapcapsule)
instance.snapcapsules = snapcapsule
instance.save()
return instance
这是前端请求。无论出于何种原因,以这种格式发送发送请求时,django validatedData为空。我相信FormData确实知道如何处理数组。 (MyForm是一个已安装的FormData类)我也尝试了JSON.stringify(capsule),但它不起作用。 Can I append an array to 'formdata' in javascript?
export default class CapsuleForm extends React.Component {
constructor (props) {
super(props);
this.state = {
userUrl: this.props.auth.domain + "/users/" + this.props.userID + "/",
dateToPost: moment().add(1, "m"),
image: null,
caption: "",
redirect: false,
invalidFormSubmit: false
};
this.handleChange = this.handleChange.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
}
handleFormSubmit(e) {
e.preventDefault();
var capsule = new MyForm();
capsule.append("dateToPost", this.state.dateToPost.format());
capsule.append("image", this.state.image);
capsule.append("caption", this.state.caption);
var snapcapsules = new MyForm();
snapcapsules.append("snapcapsules", [capsule])
axios.patch(this.state.userUrl, snapcapsules)
.then(() => {
this.setState({redirect: true})
}).catch(err =>{
alert(err);
})
}