01
Апр
2021

Django & React: JWT Authentication Почему я не могу редактировать задачу после login?

Я пометил метод как @login_required, для того чтобы только залогинившись пользователь мог редактировать задачу, но после того как залогинился я все еще не могу редактировать задачу.

Frontend

editTask = e => {
    e.preventDefault();
    axios.post(API_URL + "/task-update/" + this.state.id + "/", this.state).then(() => {
      this.props.resetState();
      this.props.toggle();
    });
  };
    

models

class Task (models.Model):
    userName = models.CharField(max_length=8, default='')
    email = models.CharField(max_length=40, default='')
    textTask = models.CharField(max_length=250, default='')
    statusTask = models.IntegerField(null=False, default=0)

serializers

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'


class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('username',)


class UserSerializerWithToken(serializers.ModelSerializer):

    token = serializers.SerializerMethodField()
    password = serializers.CharField(write_only=True)

    def get_token(self, obj):
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(obj)
        token = jwt_encode_handler(payload)
        return token

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    class Meta:
        model = User
        fields = ('token', 'username', 'password')

views.py

@api_view(['POST'])
@login_required # Не могу редактировать задачу после login!
def taskUpdate(request, pk):
    task = Task.objects.get(id=pk)
    serializer = TaskSerializer(instance=task, data=request.data)
    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)

@api_view(['GET'])
def current_user(request):
    """
    Determine the current user by their token, and return their data
    """
    
    serializer = UserSerializer(request.user)
    return Response(serializer.data)


class UserList(APIView):
    """
    Create a new user. It's called 'UserList' because normally we'd have a get
    method here too, for retrieving a list of all User objects.
    """

    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = UserSerializerWithToken(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

urls

urlpatterns = [
    path('', views.apiOverview, name="api-overview"),

    path('token-auth/', obtain_jwt_token),
    path('current_user/', current_user),
    path('users/', UserList.as_view()),

    path('task-list/', views.taskList, name="task-list"),
    path('task-detail/<str:pk>/', views.taskDetail, name="task-detail"),
    path('task-create/', views.taskCreate, name="task-create"),
    path('task-update/<str:pk>/', views.taskUpdate, name="task-update"),
    path('task-delete/<str:pk>/', views.taskDelete, name="task-delete"),
]

Источник: https://ru.stackoverflow.com/questions/1264835/django-react-jwt-authentication-%D0%9F%D0%BE%D1%87%D0%B5%D0%BC%D1%83-%D1%8F-%D0%BD%D0%B5-%D0%BC%D0%BE%D0%B3%D1%83-%D1%80%D0%B5%D0%B4%D0%B0%D0%BA%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C-%D0%B7%D0%B0%D0%B4%D0%B0%D1%87%D1%83-%D0%BF%D0%BE%D1%81%D0%BB%D0%B5-l

Тебе может это понравится...

Добавить комментарий