如何使ModelViewSet接受POST方法创建对象?当我尝试呼叫端点时,我得到405 'Method "POST" not allowed.'。
在views.py中:
class AccountViewSet(viewsets.ModelViewSet):
"""An Account ModelViewSet."""
model = Account
serializer_class = AccountSerializer
queryset = Account.objects.all().order_by('name')
在serializers.py中:
class AccountSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=False)
active_until = serializers.DateTimeField()
class Meta:
model = Account
fields = [
'name',
'active_until',
]
def create(self, validated_data):
with transaction.atomic():
Account.objects.create(**validated_data)
在urls.py中:
from rest_framework import routers
router = routers.SimpleRouter()
router.register(
prefix=r'v1/auth/accounts',
viewset=AccountViewSet,
base_name='accounts',
)
我需要创建一个特定的@action?我这样做的尝试尚未成功。如果是url = reverse('app:accounts-<NAME>')这样的话,我可以从测试中调用它吗?我还没有找到完整的示例(urls.py,views.py,serializers.py和测试等)。
largeQ
相关分类