我正在尝试使用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发布数据:
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);
});
}
如何使用默认方法(create / update / partial_update)或者使用默认方法(create / update / partial_update),使用发布数据在模型视图集类中使用Django和django rest框架创建或更新request.user
的profile_picture创建新的detail route
?
答案 0 :(得分:6)
假设您的JS使用' detailed_route
'发布请求(选中this),您应该能够在创建或更新用户时上传图像文件。另外,请务必发送CSRF Token。
为了能够自行设置徽标,none
是使用仅限于徽标的序列化程序的好方法。
在详细路线中,如果您要为登录用户上传日志(我看到您将get_object
作为ID),您可以在调用class UserLogoSerializer(serializers.ModelSerializer):
class Meta:
model = UserDetail
fields = ['profile_picture']
class UserDetailViewSet(viewsets.ModelViewSet):
queryset = UserDetail.objects.all()
serializer_class = UserDetailSerializer
permission_classes = [AllowAny]
@detail_route(methods=['post'])
def set_profile_picture(self, request, pk=None, format=None):
if pk in ['none', 'self']: # shortcut to update logged in user without looking for the id
try:
userdetail = self.get_queryset().get(user=request.user)
except UserDetail.DoesNotExist:
userdetail = None
else:
userdetail = self.get_object()
serializer = serializers.UserLogoSerializer(userdetail, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
之前在详细路线中检查该内容,这将获得用户详细信息实例
permission_classes
如果我没记错的话,document.addEventListener('deviceready', deviceReady());
是默认情况下Viewset上设置的一个,默认解析器应该完成这项工作。
答案 1 :(得分:4)