Method POST not allowed with Django Rest Framework

2024/7/6 22:17:29

I'm trying to create a JSON API compliant rest service using Django Rest Framework JSON API: https://django-rest-framework-json-api.readthedocs.io/en/stable/index.html

I think I'm stuck at the Django Rest Framework level, but I am not certain.

I think the GET request is working, but the POST is not because I get this response:

$ curl -H 'Accept: application/vnd.api+json; indent=2' -X POST http://localhost:8000/greeters/
{"errors": [{"detail": "Method \"POST\" not allowed.","source": {"pointer": "/data"},"status": "405"}]
}

But the GET is fine:

$ curl -H 'Accept: application/vnd.api+json; indent=2' http://localhost:8000/greeters/
{"data": {}
}

I've looked at other posts and the tutorials and it seems like I've missed something in my code that is not popping out at me. Hopefully, it will pop out at someone else who has more experience with Djang and Django Rest Framework.

Thank you for your time :)

Here's my code:

my_project/urls.py

from django.conf.urls import include
from django.contrib import admin
from django.urls import path, re_pathurlpatterns = [path('admin/', admin.site.urls),re_path(r'^greeters/', include('greeter.urls')),
]

greeter/urls.py

from django.conf.urls import url, include
from rest_framework import routers
from .views import GreeterViewSetROUTER = routers.DefaultRouter()
ROUTER.register(r'^', GreeterViewSet)urlpatterns = [url(r'^', include(ROUTER.urls)),
]

greeter/views.py

from rest_framework import viewsets
from .models import Greeter
from .serializers import GreeterSerializerclass GreeterViewSet(viewsets.ModelViewSet):"""API endpoints for Greeter"""queryset = Greeter.objects.all()serializer_class = GreeterSerializer# I've tried adding these methods in but none of it worked#def perform_create(self, serializer):#    serializer.save(owner=self.request.user)#def create(self, request):#    print('#########create')#def post(self, request):#    print('#########post')

greeter/serializers.py

from rest_framework import serializers
from .models import Greeterclass GreeterSerializer(serializers.HyperlinkedModelSerializer):"""Define Greeter serializer"""class Meta:model = Greeterfields = ('message')

greeter/models.py

from django.db import modelsclass Greeter(models.Model):"""Define Greeter model"""id = models.CharField(primary_key=True,max_length=200)message = models.CharField(max_length=200)

Update:

Thank you for the help. It has guided me to the solution.

I removed greeter/urls.py and moved all of the url configurations into my_project/urls.py.

from django.conf.urls import include
from django.contrib import admin
from django.urls import path, re_path
from rest_framework import routers
from greeter.views import GreeterViewSetROUTER = routers.DefaultRouter()
ROUTER.register(r'greeters', GreeterViewSet)urlpatterns = [path('admin/', admin.site.urls),re_path(r'^', include(ROUTER.urls)),
]

It works, but I would still like to understand how to push all of the greeter url code into a file inside the greeter folder, like greeter/urls.py.

I've opened up a separate question to get guidance on that so I can mark this as answered.

In Django, how do you keep a module's url configurations encapsulated inside the module?

Thanks again for all of the help :)

Answer

Add some API prefix to your url include statement as,

urlpatterns = [url(r'sample', include(ROUTER.urls)),
]


Thus your end-point will be, /greeters/sample/ for list-api (HTTP GET) and create api (HTTP POST)

https://en.xdnf.cn/q/119209.html

Related Q&A

Running multiple queries in mongo`

I have a collection and want to get a set of results that met a set of conditions. I understand the Mongo doesnt let you use joins so I would need to run separate queries and join the results into a si…

Error in Calculating neural network Test Accuracy

I tried to train my neural network, and then evaluate its testing accuracy. I am using the code at the bottom of this post to train. The fact is that for other neural networks, I can evaluate the testi…

Adding stats code to a function in Python

Im relatively new to Python and trying to learn how to write functions. The answer to this post highlights how to get certain stats from a dataframe and I would like to use it in a function.This is my…

Multiple Histograms, each for a label of x-axis, on the same graph matplotlib

I am trying to plot a graph to show different behaviors by males and females with regards to a certain activity, for different age-groups. So, if the age groups are: [1-10,11-20,21-30...] I would like …

How can I split a string in Python? [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicates:Split python string every nth character?What is the most “pythonic” way to iterate over a list in chu…

How to enable media device access in Edge browser using Selenium?

I have a Selenium test I want to run in Edge against a page which uses the webcam and microphone. In order for those media devices to work in the browser, the user has to allow the site access to the d…

Print specific rows that are common between two dataframes

i have a dataframe (df1) like this id link 1 google.com 2 yahoo.com 3 gmail.comi have another dataframe(df2) like this: id link numberOfemployees 1 linkedin.com …

What is the problem with buttons connection in PyQt5?

I have the problem that I cannot connect the implementation between two buttons. After I pressed the "Grayscale" button and got the grayscale image, I pressed the "Canny" button but…

Install ipykernel in vscode - ipynb (Jupyter)

Greetings! I am not able to install ipykernel and receiving following error. Please advise. print(Hello) Running cells with Python 3.10.5 64-bit requires ipykernel package. Run the following command to…

How do I write a form in django

I am writing a forums app for my final project in class and I am trying to write a form for creating a new thread, Basically all I need it to do is username: text box hereName of thread: Text box here…