Cannot post to DRF modelviewset - request.data imm

2019-05-26 16:25发布

问题:

I've done what feels like the absolute minimum in setting up a rest endpoint in front of a django model, but I cannot post to it from the browseable API.

On djangorestframework==3.3.0, all posts to /api/transactions/ are rejected.

models.py

class TransactionQuerySet(models.QuerySet):
    ...

class Transaction(models.Model):
    objects = TransactionQuerySet.as_manager()

    id = models.UUIDField(primary_key=True,
                          editable=False,
                          default=uuid4,
                          unique=True)

    description = models.CharField(max_length=120)
    timestamp = models.DateTimeField(default=get_timestamp,
                                     editable=False)
    amount = models.DecimalField(max_digits=8, decimal_places=2)

    def __unicode__(self):
        return '{0} ({1})'.format(self.description,
                                  to_decimal(self.amount))

    class Meta:
        ordering = ['-timestamp']

serializers.py

class TransactionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Transaction
        exclude = ()

views.py

class TransactionViewSet(viewsets.ModelViewSet):
    queryset = Transaction.objects.all()
    serializer_class = TransactionSerializer

tracking.urls

from rest_framework.routers import DefaultRouter
from django.conf.urls import url

import views

router = DefaultRouter()
router.register(r'transactions', views.TransactionViewSet)
urlpatterns = router.urls

urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/', include('tracking.urls')),
]

Submitting the form gets this response

HTTP 400 Bad Request
Content-Type: application/json
Vary: Accept
Allow: GET, POST, HEAD, OPTIONS

{
    "amount": [
        "This field is required."
    ],
    "description": [
        "This field is required."
    ]
}

Am I missing something?

回答1:

I can post to the endpoint with authentication disabled. Apparently, it is related to this bug in DRF