无法在Django-rest API中使用POST请求存储数据

时间:2019-02-07 00:28:14

标签: django-rest-framework

免责声明:-我是初学者。 我正在尝试构建一个可以支持所有CRUD操作的Django REST API。 我能够从API调用(127.0.0.1/api/get)获取数据,还能够从UI(在GET请求之后)手动添加,修改和删除记录。 我在模板目录中创建了一个表单,该表单接收用户的输入,并在提交时将其转到相同的url(127.0.0.1/api/get),但未保存数据,而是返回此:- HTTP 400错误请求 允许:GET,POST,HEAD,OPTIONS 内容类型:application / json 有所不同:接受

{     “ sourceName”:[         “这是必填栏。”     ],     “ sourceURL”:[         “这是必填栏。”     ] }

我只有一个应用程序(源)。 views.py:-

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from source import models
from source import serializers
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.views import APIView

def home(request):
    return render(request, 'Forms/input.html')

class SourceViewset(viewsets.ModelViewSet):
    print("Inside ConnectionInfoViewset..")
    queryset = models.Source.objects.all()
    serializer_class = serializers.SourceSerializer
    print("Inside ConnectionInfoViewset..")

    def post(self,request):
        print("Inside POST")
        return JsonResponse("From POST", safe=False)
        serializer = serializers.SourceSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


source_urls.py
from django.urls import path, include
from source import views
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('', views.SourceViewset)

urlpatterns = [
    path('', views.home),
    path('get/', include(router.urls)),
]

serializers.py:-

from rest_framework import serializers
from source import models
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt

class SourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Source
        # fields = '__all__'
        fields = ('sourceName','sourceURL')

models.py:- 

from django.db import models

# Create your models here.

class Source(models.Model):
    sourceName =  models.CharField(max_length = 40)
    sourceURL = models.CharField(max_length = 40)    

def __str__(self):
    return self.__all__

input.html:- 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form action="/api/get/"  method = "POST">
        {% csrf_token %}
        <input type="text" placeholder="SourceName" name = 'user_name'> <br>
        <input type="text" placeholder="SourceURL" name = 'password'><br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

这是在DRF包中定义视图集的方式,您可以在各个块中编写自定义的方法代码。

class UserViewSet(viewsets.ViewSet):
"""
Example empty viewset demonstrating the standard
actions that will be handled by a router class.

If you're using format suffixes, make sure to also include
the `format=None` keyword argument for each action.
"""

def list(self, request):
    pass

def create(self, request):
    pass

def retrieve(self, request, pk=None):
    pass

def update(self, request, pk=None):
    pass

def partial_update(self, request, pk=None):
    pass

def destroy(self, request, pk=None):
    pass

另一件事是您不能使用相同的表单进行PUT,您需要捕获ajax中的Submit并调用API。就是这样。

答案 1 :(得分:0)

class SourceViewset(viewsets.ModelViewSet):
    def list(self, request):
        print("inside list")
        queryset = models.Source.objects.all()
        serializer_class = serializers.SourceSerializer

    def create(self, request):
        serializer = serializers.SourceSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

您的意思是要实现自定义GET和POST请求处理程序,它应该看起来像这样吗?对于上面的示例,由于它无法正常工作。很明显,我缺少一些内容,您可以更正此示例GET和POST吗?