在Django REST Framework中,可以通过以下步骤将当前活动用户作为外键添加到创建post模型中:
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes, authentication_classes
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['title', 'content']
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
permission_classes = [IsAuthenticated]
authentication_classes = [TokenAuthentication]
def perform_create(self, serializer):
serializer.save(user=self.request.user)
from django.urls import include, path
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'posts', PostViewSet)
urlpatterns = [
path('', include(router.urls)),
]
现在,当创建一个新的Post对象时,该对象将与当前活动用户关联,并保存到数据库中。同时,只有经过身份验证的用户才能执行此操作,确保安全性。
这里是一些相关链接和推荐的腾讯云产品:
请注意,这里只提供了一种解决方案,实际情况可能因项目需求而异。
领取专属 10元无门槛券
手把手带您无忧上云