繁体   English   中英

如何将令牌有效负载的“user_id”放入 JSON POST 表单中?Django REST、simpleJWT、Vue3

[英]How do you get the "user_id" of the token payload into the JSON POST form?Django REST, simpleJWT, Vue3

所以我可以在本地存储中访问和刷新令牌。 解码的访问令牌在有效负载中具有"user_id" 我在理解如何向 REST API 发出 POST 请求时遇到问题,其中 JSON 表单包含当前登录用户的"user_id" 我是从存储的 JWT 中获取它还是有其他方法?

对于有效的 POST 请求,我需要 3 个字段:

{
"post_author": "field, which needs the currently logged in user, aka user_id from the token "
"post_body": "some text"
"post_title": "some text"
}

简化问题,如何将解码后的token的"user_id"转成JSON形式?

创建Post.vue

<template>
  <div id="authenticationDiv">
    <div>
      <input type="text" v-model="postTitle" placeholder="post_title" />
      <input type="text" v-model="postBody" placeholder="post_body" />
    </div>
    <br />
    <button @click="createPost">Submit Post</button>
  </div>
</template>

<script>
import {  getPosts } from "./importable_functions";
import { ref } from "vue"

export default {
  setup() {
    const ACCESS_TOKEN = "access_token";
    
    const postTitle = ref("");
    const postBody = ref("");

    async function createPost() {
      // var csrftoken = getCookie("csrftoken");
      fetch("http://127.0.0.1:8000/api/create_post/", {
        method: "POST",
        headers: {
          "Content-type": "application/json",
          // "X-CSRFToken": csrftoken,
          Authorization: `Bearer ${window.localStorage.getItem(ACCESS_TOKEN)}`,
        },
        body: JSON.stringify({
          post_body: postBody.value,
          post_title: postTitle.value,
          // post_author: 
        }),
      }).then((response) => {
        getPosts();
        return response;
      });
    }
    
    return {
      postTitle,
      postBody,
      createPost,
    };
  },
};
</script>

views.py create_post 视图

@api_view(['POST'])
def create_post(request):
    serializer = PostSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save(post_author=request.user)
    return Response(serializer.data)

序列化程序.py

class PostSerializer(serializers.ModelSerializer):
    post_author_username = serializers.ReadOnlyField(source="post_author.username")
    post_author = serializers.ReadOnlyField(source="post_author")

    class Meta:
        model = Post
        fields = '__all__'

models.py - 发布和自定义用户模型

class Post(models.Model):
    post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts')
    post_title = models.CharField(max_length=200)
    post_body = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.post_title

class CustomUser(AbstractUser):
    fav_color = models.CharField(blank=True, max_length=120)

您可以在 JSON 中发送post_titlepost_body并在保存期间添加用户 ID:

@api_view(['POST'])
def create_post(request):
    serializer = PostSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save(post_author=request.user) # add post author
    return Response(serializer.data)

请记得更新序列化程序,我认为将post_author设置为只读字段会很好。

class PostSerializer(serializers.ModelSerializer):
    post_author_username = serializers.ReadOnlyField(source="post_author.username")

    class Meta:
        model = Post
        read_only_fields = (post_author_username, post_author)
        fields = (post_author_username, post_author, post_title, post_body)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM