0
我試圖在django rest框架中實現用戶配置文件。根據django rest框架中的身份驗證方法使用不同的序列化程序
用戶應該能夠請求其他用戶的配置文件;但是,由於配置文件包含敏感信息,因此我想限制在請求配置文件時返回給非所有者和未經認證的用戶的信息。
我正在尋找一個測試,我可以在我的視圖方法中運行,這將確定哪個序列化器用於該請求。
我該怎麼做?
# models.py
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile')
bio = models.CharField(max_length=100)
# dob is sensitive and should be protected...
dob = models.DateTimeField(blank=True, null=True)
我的串行器應該是這樣的:
# serializers.py
# Only for the owner...
class ProfileOwnerSerializer(serializers.HyperlinkedModelSerializer):
user = serializers.ReadOnlyField(source='user.id')
first_name = serializers.ReadOnlyField(source='user.first_name')
last_name = serializers.ReadOnlyField(source='user.last_name')
class Meta:
model = Profile
fields = (
'url',
'id',
'dob', #sensitive
'user',
'first_name',
'last_name', #sensitive
)
#For logged in users...
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
user = serializers.ReadOnlyField(source='user.id')
first_name = serializers.ReadOnlyField(source='user.first_name')
class Meta:
model = Profile
fields = (
'url',
'id',
'bio',
'user',
'first_name',
)
#For everyone else...
class NonAuthProfileSerializer:
...
而且我會嘗試在這裏把它們區別開...
# views.py
class ProfileDetail(APIView):
"""
Retrieve a profile instance.
"""
# Can't user permission_classes bc I want to cater to different classes...
def get_object(self, pk):
try:
return Profile.objects.get(pk=pk)
except Profile.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
profile = self.get_object(pk)
# is_owner = ???
# is_authenticated = ???
# Define the serializer to be ProfileSerializer, ProfileOwnerSerializer, etc.
serializer = CorrectSerializer(
profile,
context={"request": request},
)
return Response(serializer.data)
我不認爲它會是太很難檢查請求是否由所有者發送,因爲我可以交叉引用配置文件ID。
但是,如何檢查用戶是否已登錄?我試着在查看方法中查看request.user.auth
,但是看起來是None
是否請求已登錄。