我正在尝试使用Vuejs和Django上传图片,但是我无法解决它。
这是Django的部分代码:
class UserDetail(models.Model):
user = models.OneToOneField(User)
profile_picture = models.ImageField(upload_to=create_file_path)
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = UserDetail
fields = '__all__'
class UserDetailViewSet(viewsets.ModelViewSet):
queryset = UserDetail.objects.all()
serializer_class = UserDetailSerializer
permission_classes = [AllowAny]
@detail_route(permission_classes=[AllowAny], methods=['POST'], parser_classes=[FormParser, MultiPartParser])
def create_or_update_profile_picture(self, request):
user = request.user
#
# how to create or update user detail profile picture ?
#
我会用以下方式从Vuejs发布数据: 我从Vuejs这样发布数据:
changeProfilePicture() {
const file_input = document.getElementById('display_profile_image');
const img = file_input.files[0];
let formData = new FormData();
formData.append("profile_picture", img);
const url = this.$store.state.website + '/api/accounts/user-detail/none/create_or_update_profile_picture/';
this.$http.post(url, formData)
.then(function (response) {
this.$store.dispatch('getUserDetail');
})
.catch(function (response) {
console.log(response);
});
}
如何使用POST数据在Django和Django Rest Framework的模型视图集类中使用默认方法(create/update/partial_update)或通过创建新的详细路由来创建或更新 request.user
的 profile_picture
?