Search code examples
djangodjango-rest-frameworkdjango-viewsdjango-serializerdjango-rest-auth

How can I make sure that the data is from the login user in Django?


I'm trying to save the data I've received from Arduino in the DB. We have succeeded in receiving and storing temperature and humidity data, but failed to link this data with logged-in users. Can you help me? Here is my code.

views.py

from .models import arduino
from .serializers import arduinoSerializers
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView

class arduinoToAndroidViewSet (ViewSet) :
    def dataSend (self, request) :
        user = self.request.user
        queryset = arduino.objects.filter(name = user)
        serializer = arduinoSerializers(queryset, many=True)
        return Response(serializer.data)

class arduinoToDatabaseViewSet (CreateAPIView) :
    serializer_class = arduinoSerializers

    def get_queryset(self) :
        user = self.request.user
        return arduino.objects.filter(name = user)

    def dataReceive(self, request) :
        queryset = get_queryset()
        serializer = arduinoSerializers(queryset, many=True)
        if serializer.is_valid() :
            serializer.save()
        return Response(serializer.data)

serializers.py

from rest_framework import serializers
from .models import arduino

class arduinoSerializers (serializers.ModelSerializer) :
    name = serializers.CharField(source='name.username', read_only=True)
    class Meta :
        model = arduino
        fields = ('name', 'temp', 'humi')

enter image description here

If you post it like this,

enter image description here

I want you to know that this is root's data. enter image description here I log in to the test account, put the data in, and press the post button. enter image description here This will not Migrate to the 'test' account. I want to migrate this data in conjunction with the 'test' account.


Solution

  • you could use permissions to limit access

    and for linking user to your data, add perform_create function (i assume name field is FK to user)

    from rest_framework.permissions import IsAuthenticated
    from rest_framework.generics import CreateAPIView
    
    
    class arduinoToDatabaseViewSet(CreateAPIView):
        permission_classes = [IsAuthenticated]  # only logged in users has access to this view
    
        def perform_create(self, serializer):
            serializer.save(name=self.request.user)