对不起,我还是一个django的初学者,我想用django rest_framework创建一个enpoint,允许我创建一个HD钱包和备份数据库,但我有一个错误:不允许方法“POST”。
所以我创建了这个模型来代表hdwallet:
from typing import Any
from django.db import models, transaction
from django.contrib.auth.models import User
class HDWallet(models.Model):
"""HDWallet class"""
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
name: str = models.CharField(max_length=255, unique=True)
private_key: str = models.CharField(max_length=100, unique=True)
address: str = models.CharField(max_length=100, unique=True)
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="wallet",
)
active = models.BooleanField(default=True)
def __str__(self) -> str:
return self.name
@transaction.atomic
def disable(self) -> Any:
if self.active is False:
# Ne faisons rien si la wallet est déjà désactivée
return
self.active = False
self.save()
self.currencies.update(active=False)
我还创建了我的serializers类:
class HDWalletSerializer(ModelSerializer):
class Meta:
model = HDWallet
fields = "__all__"
def post(self, request: Request) -> Any:
user = User.objects.get(username=request["username"])
name = f"{user.username}_{user.id}"
wallet = Wallet.create(name)
if user is not None:
hdwallet = HDWallet.objects.create(
{
"name": name,
"private_key": wallet.get_key(),
"address": wallet.get_key().address,
"user": user.id,
}
)
else:
raise Exception("use do not exist")
return Response(
{
"status": 201,
"message": "wallet have been successfully created!",
"data": hdwallet,
}
)
和我在www.example.com上的观点views.py:
class HDWalletCreateView(ModelViewSet):
serializer_class = HDWalletSerializer
permission_classes = [IsUser, IsUserAuthenticated, IsAdminAuthenticated]
这就是URL:
# we create your router
router = routers.SimpleRouter()
# we register all url
router.register("wallet/create", HDWalletCreateView, basename="wallet-create"),
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include(router.urls)),
]
但是当我运行endpoint to postman时,我遇到了这个错误:“detail”:“Method“POST”not allowed.”我不知道问题出在哪里
1条答案
按热度按时间jchrr9hc1#
最后我解决了这个问题,我落在web文档谁帮助我有一个很好的理解如何执行crud使用DRF。所以这就是解决方案,我会把链接到网络教程在最后。我的钱包类的模型没有改变:
这是我的serializer类:
这是我的views文件:
最后是URL文件:
https://www.bezkoder.com/django-rest-api/