我在獲取當前用戶在django rest框架中上傳圖像時遇到了很多麻煩。在django rest框架中獲取當前用戶
Django rest框架是用於網頁的純django內的應用程序。
我使用django rest框架,以便用戶可以上傳我們的服務器上的文件......除了我們需要知道誰是上傳它的用戶,一切都很好。我真的嘗試過很多這個網站和谷歌提供的解決方案,但只是無法實現。這是來自應用程序的代碼。我們該做什麼?
viewset.py
from rest_framework import viewsets, filters
from api.serializers import UploadedImageSerializer # import our serializer
from api.models import UploadedImage # import our model
class UploadedImagesViewSet(viewsets.ModelViewSet):
queryset = UploadedImage.objects.order_by('-id')[:1]
serializer_class = UploadedImageSerializer
serializer.py
from rest_framework import serializers
from api.models import UploadedImage # Import our UploadedImage model
class UploadedImageSerializer(serializers.ModelSerializer):
# Create a custom method field
# current_user = serializers.SerializerMethodField('_user')
class Meta:
model = UploadedImage
fields = ('id', 'image','name','Tip','curent_user') # only serialize the primary key and the image field
models.py
from django.db import models
import uuid,os
import sqlite3
import Function1
import Function2
from django.contrib.auth.models import User
def scramble_uploaded_filename(instance, filename):
extension = filename.split(".")[-1]
return "{}.{}".format(uuid.uuid4(), extension)
def filename(instance, filename):
return filename
# Our main model: Uploaded Image
class UploadedImage(models.Model):
image = models.ImageField("Uploaded image",upload_to=scramble_uploaded_filename)
Tip = models.IntegerField("Captcha type")
curent_user = models.CharField("Curent user",editable=False,max_length=100,default='')
def filen(self) :
path = self.image.path
tip = self.Tip
writez = Function1.File_input(path,tip)
text = Function2.File_input (writez,0.83,tip)
return text
name = filen
views.py
from rest_framework import viewsets
from api.serializers import UploadedImageSerializer
from api.models import UploadedImage
class UploadViewSet(viewsets.ModelViewSet):
"""
API endpoint
"""
queryset = UploadedImage.objects.all()
serializer_class = UploadedImageSerializer
我的代碼有了一些進步,它幫助我理解了它的工作原理。我找到後我會回覆你。 Ty爲您提供幫助。 –
我做了tnx人! –
所以它顯示在管理員?你寫的其他評論是什麼?有麻煩的ID?聽起來像你需要定義def'__str __(self): \t \t返回模型中的self.user.userprofile.name'。我的代碼是否爲您提供解決方案,或者您找到了自己的解決方案?無論如何,我很高興你做到了。 – hansTheFranz