django 在插入数据时发布方法

问题描述 投票:0回答:0

在一个django项目中,我想在后端插入标题、类别、图像。 在那件事上,if 语句在运行程序时不起作用。

这是我的表格

 <form action="" enctype="multipart/form-data" method="POST" class="p-4">
            {% csrf_token %}
            <div class="row">
              <div class="col-md-12 mb-3">
                <div class="form-group">
                  <label for="title">Title</label>
                  <input type="text" class="form-control p-3" placeholder="title" name="title">
                </div>
              </div>
              <div class="col-md-12 mb-3">
                <div class="form-group">
                  <label for="category">Category</label>
                  <select id="category" class="form-control form-select p-3" name="category">
                    <option value="none">Select a category</option>
                    {% for opt in category %}
                    <option value="{{ opt }}">{{ opt }}</option>
                    {% endfor %}
                  </select>
                </div>
              </div>
              <div class="col-md-12 mb-3">
                <div class="form-group">
                  <input type="file" class="form-control p-3" name="image">
                </div>
              </div>
              <div class="mt-3 col-md-12">
                <button class="btn btn-primary" style="width: 100%;">Upload</button>
              </div>
            </div>
          </form>

这是我的观点

def add(request):
    if request.method == 'POST':
        print("POST request received")
        title = request.POST.get('title')
        cat = request.POST.get('category')
        image = request.FILES.get('image')
        print(title, cat, image)
    else:
        print("GET request received")
        categories = addcategory.objects.all()
        context = {
            'category': categories,
        }
        return render(request, 'add.html', context)

终端输出:

GET request received
[07/Apr/2023 05:49:28] "GET /add/?csrfmiddlewaretoken=il3U1rnxUl5217Wud9i1kX6TfMNk7uOoQDfUYxYb8UlYZIczG4Uz4OgR6nib4yrF&title=veg&category=Food&image=food.jpeg HTTP/1.1" 200 4672

我想打印“收到的POST请求”。

python html django forms post
© www.soinside.com 2019 - 2024. All rights reserved.