added support for user profiles
This commit is contained in:
parent
eeb74027eb
commit
1f314f1c20
8 changed files with 137 additions and 32 deletions
|
@ -1,10 +1,13 @@
|
|||
from django.contrib.auth.models import User, Group
|
||||
from django.contrib.auth.models import User
|
||||
from django.http import JsonResponse
|
||||
from knox.auth import TokenAuthentication
|
||||
from rest_framework import viewsets, permissions, status
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.decorators import api_view, action
|
||||
from rest_framework.response import Response
|
||||
|
||||
from users.serializers import UserSerializer, GroupSerializer
|
||||
from users.models import UserProfile
|
||||
from users.permissions import ReadOnly
|
||||
from users.serializers import UserSerializer, UserProfileSerializer
|
||||
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
|
@ -15,6 +18,51 @@ class UserViewSet(viewsets.ModelViewSet):
|
|||
serializer_class = UserSerializer
|
||||
|
||||
|
||||
class UserProfileViewSet(viewsets.ModelViewSet):
|
||||
authentication_classes = [TokenAuthentication]
|
||||
permission_classes = [permissions.IsAuthenticated | ReadOnly]
|
||||
|
||||
queryset = UserProfile.objects.all()
|
||||
serializer_class = UserProfileSerializer
|
||||
lookup_field = "user__username"
|
||||
|
||||
@action(detail=False)
|
||||
def current_user_profile(self, request, *args, **kwargs):
|
||||
try:
|
||||
user = request.user
|
||||
except User.DoesNotExist:
|
||||
return Response([], status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
try:
|
||||
user_profile = UserProfile.objects.get(user=user)
|
||||
except UserProfile.DoesNotExist:
|
||||
user_profile = UserProfile(
|
||||
user=user,
|
||||
)
|
||||
|
||||
user_profile.save()
|
||||
|
||||
return JsonResponse(UserProfileSerializer(user_profile).data)
|
||||
|
||||
def retrieve(self, request, pk=None, *args, **kwargs):
|
||||
try:
|
||||
username = kwargs.get('user__username')
|
||||
user = User.objects.get(username=username)
|
||||
except User.DoesNotExist:
|
||||
return Response([], status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
try:
|
||||
user_profile = UserProfile.objects.get(user=user)
|
||||
except UserProfile.DoesNotExist:
|
||||
user_profile = UserProfile(
|
||||
user=user,
|
||||
)
|
||||
|
||||
user_profile.save()
|
||||
|
||||
return JsonResponse(UserProfileSerializer(user_profile).data)
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
def register(request):
|
||||
user_data = UserSerializer(data=request.data)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue