如何解决django rest_framework错误“Method \“POST\”not allow."?

fxnxkyjh  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(188)

对不起,我还是一个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.”我不知道问题出在哪里

jchrr9hc

jchrr9hc1#

最后我解决了这个问题,我落在web文档谁帮助我有一个很好的理解如何执行crud使用DRF。所以这就是解决方案,我会把链接到网络教程在最后。我的钱包类的模型没有改变:

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)
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="wallet",
    )

    active = models.BooleanField(default=True)

    def __str__(self) -> str:
        return self.name

这是我的serializer类:

class HDWalletSerializer(ModelSerializer):
    class Meta:
        model = HDWallet
        fields = "__all__"

这是我的views文件:

@api_view(["GET", "POST", "DELETE"])
def wallet_list(request):
    if request.method == "GET":
        wallets = HDWallet.objects.all()

        name = request.query_params.get("name", None)
        if name is not None:
            wallets = wallets.filter(name=name)

        tutorials_serializer = HDWalletSerializer(wallets, many=True)
        return JsonResponse(tutorials_serializer.data, safe=False)

    elif request.method == "POST":
        wallet_data = request.data
        wallet_serializer = HDWalletSerializer(data=wallet_data)
        if wallet_serializer.is_valid():
            wallet_serializer.save()
            return JsonResponse(wallet_serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(
            wallet_serializer.errors, status=status.HTTP_400_BAD_REQUEST
        )

    elif request.method == "DELETE":
        count = HDWalletSerializer.objects.all().delete()
        return JsonResponse(
            {"message": "{} Tutorials were deleted successfully!".format(count[0])},
            status=status.HTTP_204_NO_CONTENT,
        )

@api_view(["GET", "PUT", "DELETE"])
def wallet_detail(request, pk):
    try:
        wallet = HDWallet.objects.get(pk=pk)
    except HDWallet.DoesNotExist:
        return JsonResponse(
            {"message": "The wallet does not exist"},
            status=status.HTTP_404_NOT_FOUND,
        )

    if request.method == "GET":
        wallet_serializer = HDWalletSerializer(wallet)
        return JsonResponse(wallet_serializer.data)

    elif request.method == "PUT":
        wallet_data = JSONParser().parse(request)
        wallet_serializer = HDWalletSerializer(wallet, data=wallet_data)
        if wallet_serializer.is_valid():
            wallet_serializer.save()
            return JsonResponse(wallet_serializer.data)
        return JsonResponse(
            wallet_serializer.errors,
            status=status.HTTP_400_BAD_REQUEST,
        )

    elif request.method == "DELETE":
        wallet.delete()
        return JsonResponse(
            {"message": "Wallet was deleted successfully!"},
            status=status.HTTP_204_NO_CONTENT,
        )

@api_view(["GET"])
def wallet_list_published(request):
    wallets = HDWallet.objects.filter(published=True)

    if request.method == "GET":
        wallets_serializer = HDWalletSerializer(wallets, many=True)
        return JsonResponse(wallets_serializer.data, safe=False)

最后是URL文件:

from django.urls import path
from wallet.views import (
    wallet_detail,
    wallet_list,
)

urlpatterns = [
    path("api/wallets/", wallet_list),
    path("api/wallets/<pk>/", wallet_detail),
]

so that's the result here on image
[![enter image description here][1]][1]
[![enter image description here][1]][1]

We have certains configurations to do, I put the tutorial link for who want to have more explanation:

[enter link description here][1]

https://www.bezkoder.com/django-rest-api/

相关问题