You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Rest Framework报错:Method 'GET' not allowed 求助

解决Django注册接口"Method 'GET' not allowed"错误

错误原因

你的registerUser视图用了@api_view(['POST'])装饰器,这就限定了这个接口只能接受POST请求,如果用GET方法访问,自然会返回"Method 'GET' not allowed"的错误。你的URL配置本身没问题,问题出在测试时用错了请求方法。

两种处理方案

方案1:保持只接受POST(推荐,符合注册接口的设计逻辑)

不需要改任何代码,只要换用POST方法测试就行,具体测试方法看下面的「正确测试方式」。

方案2:允许GET请求(仅用于测试)

如果只是想临时用GET访问看看接口状态,可以修改装饰器,同时在视图里处理GET请求:

@api_view(['POST', 'GET'])
def registerUser(request):
    # 处理GET请求,返回提示信息
    if request.method == 'GET':
        return Response({"提示": "注册接口需要用POST方法提交数据"})
    
    # 原有的POST注册逻辑不变
    data = request.data
    user = User.objects.create(
        first_name = data['name'],
        username = data['email'],
        email = data['email'],
        password = make_password(data['password'])
    )
    serializer = UserSerializerWithToken(user, many=False)
    return Response(serializer.data)

正确测试注册接口的方式

用接口测试工具(Postman/Insomnia)

  1. 新建请求,选择POST方法
  2. 输入接口地址:http://localhost:8000/users/register/(根据你的本地服务端口调整)
  3. 在请求体里选「raw -> JSON」,填入注册数据:
{
    "name": "张三",
    "email": "zhangsan@example.com",
    "password": "zhangsan123"
}
  1. 发送请求,就能拿到带token的注册响应了。

用Python脚本测试

import requests

url = "http://localhost:8000/users/register/"
data = {
    "name": "测试用户",
    "email": "test@example.com",
    "password": "test123456"
}

response = requests.post(url, json=data)
print(response.json())

用前端表单提交

如果是做网页,确保表单的method设为POST,还要带上csrf令牌:

<form method="POST" action="/users/register/">
    {% csrf_token %}
    <input type="text" name="name" placeholder="请输入姓名">
    <input type="email" name="email" placeholder="请输入邮箱">
    <input type="password" name="password" placeholder="请输入密码">
    <button type="submit">注册</button>
</form>

内容的提问来源于stack exchange,提问作者Martin Arreola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:10:28