我的django模型如下所示:
class ExhibitionSurveyObjectSerializer(serializers.ModelSerializer):
class Meta:
model = ExhibitionSurveyObject
fields = '__all__'
def create(self, validated_data):
return ExhibitionSurveyObject.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.farmer_email = validated_data.get('farmer_email', instance.farmer_email)
instance.farmer_name = validated_data.get('farmer_name', instance.farmer_name)
instance.address = validated_data.get('address', instance.address)
instance.postal_code = validated_data.get('postal_code', instance.postal_code)
instance.size = validated_data.get('size', instance.size)
instance.path = validated_data.get('path', instance.path)
instance.object_type = validated_data.get('object_type', instance.object_type)
instance.cycle = validated_data.get('cycle', instance.cycle)
instance.save()
return instance
我有一个序列化器:
class ExhibitionSurveyObjectForm(forms.ModelForm):
owner = CustomUserChoiceField(queryset=User.objects.all())
class Meta:
model = ExhibitionSurveyObject
fields = "__all__"
我的表单:
class ExhibitionSurveyObjectList(generics.ListCreateAPIView):
queryset = ExhibitionSurveyObject.objects.all()
serializer_class = ExhibitionSurveyObjectSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
我的观点:
addObject(
name: string,
farmer_email: string,
farmer_name: string,
size: string,
path: Array<google.maps.LatLngLiteral>,
cycle: string,
object_type: string) {
let obj = new ExhibitionSurveyObjectModel(name, farmer_email, farmer_name, size, path, cycle, object_type);
let body = JSON.stringify(obj);
let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8', 'Authorization': 'Token ' + localStorage.getItem('auth_token') });
let options = new RequestOptions({ headers: headers });
console.log(body);
return this.http.post(this._exhibitionSurveyObjectURL, body, options)
.map(this.extractData)
.catch(this.handleError)
}
我有一个Ionic2前端,我的服务有以下功能来保存上述模型的实例:
export class ExhibitionSurveyObjectModel {
constructor(
public name: string,
public farmer_email: string,
public farmer_name: string,
public size: string,
public path: Array<google.maps.LatLngLiteral>,
public cycle: string,
public object_type: string,
public owner: string
){}
}
我的客户端也有一个模型:
{"owner":["This field is required."]}
正如我可以看到令牌被发送到后端,但我收到了回复{{1}}
发送令牌还不够吗?如果我必须通过&#39; 所有者&#39;以及我的服务请求应该是什么价值(但是,我认为令牌应该足够了)?
或者我在后端遗漏了什么?
答案 0 :(得分:1)
我的猜测是问题是您正在错误地创建序列化程序。您具体指明使用__all__
字段,这意味着所有字段。与此无关,但您不应该真的需要在模型serielizer上创建或更新。
相反,尝试这样的事情
class ExhibitionSurveyObjectSerializer(serializers.ModelSerializer):
class Meta:
model = ExhibitionSurveyObject
fields = ('name', 'farmer_email', 'farmer_name', 'address',
'postal_code', 'size', 'path', 'object_type',
'cycle')
read_only_fields = ('owner', )
这应该是你所需要的一切。