DRF web界面不像Postman那样工作

huangapple go评论77阅读模式
英文:

DRF web interface doesn't work as Postman

问题

以下是您提供的内容的翻译:

I'm creating a blog app where only authenticated users can add blogs. I'm using JWT tokens, and it works well on Postman, allowing me to add blogs after logging in. However, when I try to do it on the DRF web interface, it always tells me that I'm not logged in.

Exception Value: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x0000021035CA1C50>": "Blog.author" must be a "User" instance.

My views.py

class BlogList(generics.ListCreateAPIView):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    permission_classes = [IsOwnerOrReadOnly]
    
    filter_backends = [SearchFilter]
    search_fields = ["title", "content", "author__username", "author__first_name", "author__last_name"]
    
    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

Serializer.py

class BlogSerializer(serializers.ModelSerializer):
    author = serializers.ReadOnlyField(source="author.username")
    author_first_name = serializers.ReadOnlyField(source="author.first_name")
    author_last_name = serializers.ReadOnlyField(source="author.last_name")
    slug = serializers.ReadOnlyField()
    comments = serializers.PrimaryKeyRelatedField(many=True, read-only=True)
    read-only fields = ["author", "first_name", "last_name"]

    class Meta:
        model = Blog
        fields = ["id", "title", "content", "status", "author", "comments", "image",
                  "created_on", "updated_on", "author_first_name", "author_last_name", "slug"]

    def to_representation(self, instance):
        data = super().to_representation(instance)
        user = self.context["request"].user
        if not user.is authenticated:
            data.pop("slug")
        return data

    def save_author(self, **kwargs):
        if "author" not in self.validated_data:
            self.validated_data["author"] = self.context["request"].user
            return super().save(**kwargs)

    def save(self, **kwargs):
        self.validated_data["slug"] = slugify(self.validated_data.get("title"))
        return super().save(**kwargs)

I don't know what else I should post here. I tried somehow to add a button like "Authenticate" to the DRF web interface where you can post your access token, but I can't solve it.
英文:

I'am creating a blog app where only authenticate users can add blogs. I'm using JWT token and on Postman it work's well and I can add blog's after I logged in. I want to do it on DRF web interface also but it always tell me that I'm not logged in - I think.

Exception Value:	
Cannot assign &quot;&lt;django.contrib.auth.models.AnonymousUser object at 0x0000021035CA1C50&gt;&quot;: &quot;Blog.author&quot; must be a &quot;User&quot; instance.

My views.py

    class BlogList(generics.ListCreateAPIView):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
authentication_classes = [JWTAuthentication]
#permission_classes = [IsAuthenticated]
permission_classes = [IsOwnerOrReadOnly]
filter_backends = [SearchFilter]
search_fields = [&quot;title&quot;, &quot;content&quot;, &quot;author__username&quot;, &quot;author__first_name&quot;, &quot;author__last_name&quot;]
def perform_create(self, serializer):
serializer.save(author=self.request.user)
Serializer.py
class BlogSerializer(serializers.ModelSerializer):
author = serializers.ReadOnlyField(source=&quot;author.username&quot;)
author_first_name = serializers.ReadOnlyField(source=&quot;author.first_name&quot;)
author_last_name = serializers.ReadOnlyField(source=&quot;author.last_name&quot;)
slug = serializers.ReadOnlyField()
comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
read_only_fields = [&quot;author&quot;, &quot;first_name&quot;, &quot;last_name&quot;]
class Meta:
model = Blog
fields = [&quot;id&quot;, &quot;title&quot;, &quot;content&quot;, &quot;status&quot;, &quot;author&quot;, &quot;comments&quot;,  &quot;image&quot;,
&quot;created_on&quot;, &quot;updated_on&quot;, &quot;author_first_name&quot;, &quot;author_last_name&quot;, &quot;slug&quot;]
def to_representation(self, instance):
data = super().to_representation(instance)
user = self.context[&quot;request&quot;].user
if not user.is_authenticated:
data.pop(&quot;slug&quot;)
return data
def save_author(self, **kwargs):
if &quot;author&quot; not in self.validated_data:
self.validated_data[&quot;author&quot;] = self.context[&quot;request&quot;].user
return super().save(**kwargs)
def save(self,**kwargs):
self.validated_data[&quot;slug&quot;] = slugify(self.validated_data.get(&quot;title&quot;))
return super().save(**kwargs)

I don't know what else I should post here. I tried somehow to DRF web interface add some button like "Authenticate" where you can post your acces token but I can not solve it.

答案1

得分: 1

如果您使用JWT令牌来验证用户,您可以下载一些浏览器扩展,可以修改请求标头并添加它们。然后,您将令牌粘贴到那里,为标头命名,然后就可以使用了。

这是我个人使用的一个:
https://chrome.google.com/webstore/detail/modheader-modify-http-hea/idgpnmonknjnojddfkpgkljpfnnfcklj

附言:如果不关闭它,在其他网站上可能会引起一些问题,所以请记住这一点。

英文:

If you use JWT tokens to authenticate users you can download some browser extension that can modify request headers and add them. Then you paste your token there, give header a name and you are good to go.

Here is the one I personally use:
https://chrome.google.com/webstore/detail/modheader-modify-http-hea/idgpnmonknjnojddfkpgkljpfnnfcklj

p.s. can cause some issues on other websites if you don't turn it off, so keep that in mind.

huangapple
  • 本文由 发表于 2023年2月24日 04:25:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定