首页 > 解决方案 > Request.POST.get 在 django 中对我不起作用,返回默认值

问题描述

我正在尝试从 django 中的 html 表单获取输入,python 代码如下:

def add(request):
   n = request.POST.get('Username', 'Did not work')
   i = Item(name=n,price=0)
   i.save()
   return render(request,'tarkovdb/test.html')

第二张图片是我的html代码:

<html> 
    <head> 
        <meta charset="UTF-8"› 
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384—Vkoo8x4CGs0 OPaXtkKtu6ug5T0eNV6gBiFeWPGFN9Muh0f23Q9Ifjh" crossorigin="anonymous"> 
        <title>Tarkov Database Web App</title> 
    </head> 
    <body> 
        <h1>This is the page to add items</h1> 
            <li><a href="{% url 'tarkovdb:index' s'6}">List of Items in DataBase</a></li> 

<form> 
    <div class="form—group"> 
        <label for&username'> Username: </lable> 
        <input type&text' name='Username' id.'username'> <br><br> 
    </div> 
        <button type="submit" class="btn btn—primary">Submit</button> 
</form> 

标签: pythonhtmldjango

解决方案


您需要在 HTML表单标签上将方法属性设置为“发布” 。像这样:

<form method="post">
    <!-- your fields here -->
</form>

否则,您将发送一个 GET 请求,这是方法属性的默认值。

PD.:请粘贴您的代码,方便社区为您提供帮助。否则你会被否决。


推荐阅读