此字段为必填错误(Django Rest Framework & ReactJS)

tv6aics1  于 2023-04-05  发布在  React
关注(0)|答案(1)|浏览(161)

当向DRF发出POST请求时,我收到错误,此字段为必填字段。我在SO上尝试了不同的代码和其他解决方案,但没有任何成功。感谢任何帮助。
以下是我的代码片段:
views.py

class CampaignCreateAPIView(APIView):
  renderer_classes = [CampaignRenderer]
  permission_classes = [IsAuthenticated]
  def post(self, request, format=None):
    print(request.data)
    print(request.user)
    serializer = CampaignCreateSerializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        serializer.save(user=self.request.user)
        return Response({'msg':'Campaign Creation Successful'}, status=status.HTTP_201_CREATED)

renderers.py

from rest_framework import renderers
import json

class CampaignRenderer(renderers.JSONRenderer):
  charset='utf-8'
  def render(self, data, accepted_media_type=None, renderer_context=None):
    response = ''
    if 'ErrorDetail' in str(data):
      response = json.dumps({'errors':data})
    else:
      response = json.dumps(data)
    
    return response

serializers.py

class CampaignCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Campaign
        fields = ['owner', 'title', 'description', 'target', 'deadline']

urls.py

urlpatterns = [
    path('campaigns/create/', CampaignCreateAPIView.as_view(), name='campaign-create'),
]

models.py

class Campaign(models.Model):
    project_id = models.IntegerField(primary_key=True)
    owner = models.ForeignKey(User, related_name='campaigns', on_delete=models.CASCADE)
    title = models.CharField(max_length=30)
    description = models.CharField(max_length=30)
    target = models.IntegerField()
    deadline = models.DateField()
    amount_collected = models.IntegerField()
    donors = models.ManyToManyField(Donor, blank=True)

    def __str__(self):
        return self.title

React客户端:

const handleSubmit = async (e) => {
    e.preventDefault();
    // console.log({ form, access_token });
    const res = await createCampaign({ form, access_token });
    if (res.error) {
      console.log(typeof res.error.data.errors);
      console.log(res.error.data.errors);
      setServerMsg({});
      setServerError(res.error.data.errors);
    }
    if (res.data) {
      console.log(res.data);
      setServerError({});
      setServerMsg(res.data);
      console.log("Success");
      navigate("/");
    }
  };

谢谢大家。
我尝试更改所使用的通用API类。

wnvonmuf

wnvonmuf1#

尝试设置

amount_collected = models.IntegerField(default=0)

相关问题