在django rest框架中获取当前用户

时间:2017-06-16 23:19:11

标签: django python-3.x django-rest-framework

我在获取当前正在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

2 个答案:

答案 0 :(得分:2)

在我的项目中,我使用HiddenField填充当前用户。例如,对于您的情况:

class UploadedImageSerializer(serializers.ModelSerializer):
    current_user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = UploadedImage
        fields = ('id', 'image','name','Tip','current_user')

答案 1 :(得分:1)

这对我有用。你在上传类(在我的例子中是Post)中创建了一个ForeignKey并将其链接到用户(不要忘记进行迁移和迁移)。在呈现表单时的视图中,请使用String - > instance = form.save(commit = False) - > instance.uploaded_by = request.user这样您就可以获取当前用户并将其保存在Post(上传)模型中。

views.py:

instance.save()

models.py:

def upload(request):
    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit = False)
        instance.uploaded_by = request.user
        instance.save()
        form.save_m2m()

要在管理员中查看用户,您必须安装字段" uploaded_by"在你的应用程序admin.py中。我假设你知道如果不是谷歌会帮助你;) 希望有所帮助。