我正在尝试将一个带有Ajax的表单提交给Django rest-framework(3.0)ViewSet。
我可以使用curl请求提交,但我的Ajax请求给了我以下响应:
提交的数据不是文件。检查表单上的编码类型。
这是我的django-rest代码:
class UserEditSerializer(serializers.ModelSerializer):
""" Used locally to allow users to edit their user profile"""
class Meta:
model = User
include = ["about", "avatar"]
class AuthorViewSet(viewsets.ModelViewSet):
authentication_classes = (authentication.SessionAuthentication,)
permission_classes = (AllowReadonlyOrAdminOrSelf,)
parser_classes = (parsers.MultiPartParser, parsers.FormParser)
lookup_field = 'uuid'
def get_queryset(self):
return User.objects.all()
def get_serializer_class(self, *args, **kwargs):
""" Use different serializers depending on the request"""
uuid = self.kwargs.get("uuid", None)
request = self.request.method;
if request == "POST" and uuid:
return UserEditSerializer
return AuthorSerializer
def update(self, request, *args, **kwargs):
instance = self.get_object()
serializer = UserEditSerializer(instance, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
我的AJAX:
$("#profile_update_form").submit(function(e) {
var data = new FormData($(this)[0]);
e.preventDefault();
$.ajax({
url : '{% url 'api:User-detail' user.uuid %}',
type : "POST",
data : data,
enctype: 'multipart/form-data',
success : ajaxSuccessLog,
contentType : false,
processData: false,
cache: false,
error : ajaxErrorLog
});
});
我也尝试使用JQuery Form Plugin提交。调试后问题肯定发生在这里:
serializer = UserEditSerializer(instance, data=request.data, partial=True)
数据传递到序列化程序时正确。如果我不包含图像字段,我可以正确提交表单。
修改
这里要求的是我的django表单代码:
class ProfileEditForm(forms.ModelForm):
"""Form for editing user profile"""
class Meta:
model = User
fields = ['about', 'avatar']
我的表单模板:
<form id="profile_update_form" method='POST' enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
{{ author_form.as_p }}
</fieldset>
</form>