如何从请求 GET 数据创建记录(表单未通过验证)

How to create a record from request GET data (form does not pass the validation)

当我尝试从“GET”请求中插入记录时,我很困惑

我会尽量解释我想做什么。

我正在创建一个应用程序来盘点资产。

我的数据库中有 3 个 table。

我有一个主要 table 叫做 注册我公司所有资产的固定资产(“ActFijo”)。

另一种调用Inventory("Inventario"),它存储每个库存的名称

和另一个电话 Inventory_detail ("Inventario_detalle"),其中存储了被统计的详细信息或资产,以验证设备或家具没有在该位置被盗.

从主要 table ("ActFijo") 我必须搜索家具或资产并将其存储在详细信息 table ("Inventario_detalle")

我很困惑,我不知道如何处理 GET 请求,然后在一个请求中执行 POST 全部操作

我是否必须在 GET 请求中分批编写代码,然后 POST? 或者我可以在 GET 请求中执行所有操作吗?

这是我目前的代码 不知道行不行,求指导

例如我的代码没有通过表单验证。

if form.is_valid():

我正在尝试打印,但我没有看到任何验证错误,它没有打印任何东西

print(form.errors)

Views.py

from django.shortcuts import redirect, render
from .form import InventarioDetalle_Form, InventarioForm
from .models import ActFijo, Inventario, Inventario_detalle

# Create your views here.


def inventario_home_view(request):
    if request.method == "GET":
        inv = Inventario.objects.all()
        context = {"inventarios": inv}
        return render(request, "inventario/index.html", context)


def inventario_crear_view(request):
    if request.method == "POST":
        form = InventarioForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("inventario-home")
    else:
        form = InventarioForm()
    inv = Inventario.objects.all()
    context = {"formulario": form, "inventarios": inv}

    return render(request, 'inventario/crear.html', context)


def inventario_detalle_view(request, inventario):
    if request.method == "GET":
        # Obtener el valor del input "Buscar"
        codigo_activo = request.GET.get("buscar")
        print("[CODIGO ACTIVO]:", codigo_activo)
        # Buscar el activo en la bd por el campo codigo
        try:
            activo = ActFijo.objects.get(codigo=codigo_activo)
            # print(activo)
        except ActFijo.DoesNotExist:
            activo = None
        if activo:
            form = InventarioDetalle_Form(instance=activo)
            # print(form)
            print(form.errors)
            if form.is_valid():
                instance = form.save(commit=False)
                instance.inventario_id = inventario
                instance.save()
            else:
                print(
                    "This request does not pass the validation")
        else:
            print(
                "The element does not exist")
    context = {"item": Inventario_detalle.objects.all()}
    return render(request, "inventario/detalle.html", context)

form.py:

from django import forms

from .models import Inventario, Inventario_detalle


class InventarioForm(forms.ModelForm):
    class Meta:
        model = Inventario
        fields = '__all__'


class InventarioDetalle_Form(forms.ModelForm):
    class Meta:
        model = Inventario_detalle
        fields = '__all__'

url.py

from django.urls import path
from django import views
from . import views

urlpatterns = [
    path("", views.inventario_home_view, name="inventario-home"),
    path("create/", views.inventario_crear_view,
         name="inventario-create"),
    path('detail/<int:inventario>',
         views.inventario_detalle_view, name="inventario-detail"),
]

detail.html

{% extends "core/base.html" %} {% block content%}
<div class="container-fluid">
  <div class="row">
    <div class="col-md-12">
      <div class="titulo mt-5">
        <h1>Inventario Detalle</h1>
      </div>
      <form method="get">
        <input type="text" class="form-control" placeholder="Buscar Activo" name="buscar" />
      </form>
      <div style="overflow-x: auto">
        <table>
          <thead>
            <tr>
              <th>Codigo</th>
              <th>Descripcion</th>
              <th>Accion</th>
            </tr>
          </thead>
          <tbody>
            {% for i in item %}
            <tr>
              <td>{{i.codigo}}</td>
              <td>{{i.descripcion}}</td>
              <td><button type="button" class="btn btn-danger">Eliminar</button></td>
            </tr>
          </tbody>
          {% endfor %}
          </tbody>
        </table>
      </div>
      <div>{{request.GET}}</div>
    </div>
  </div>
</div>

{% endblock %}

问题就在这里

def inventario_detalle_view(request, inventario):
    if request.method == "GET":
        codigo_activo = request.GET.get("buscar")
        print("[CODIGO ACTIVO]:", codigo_activo)
        try:
            activo = ActFijo.objects.get(codigo=codigo_activo)
            print(activo)
        except ActFijo.DoesNotExist:
            activo = None
        if activo:
            form = InventarioDetalle_Form(instance=activo)
            print(form.errors)
            if form.is_valid():
                instance = form.save(commit=False)
                instance.inventario_id = inventario
                instance.save()
            else:
                print(
                    "This request does not pass the validation")
        else:
            print(
                "The element does not exist")
    context = {"item": Inventario_detalle.objects.all()}
    return render(request, "inventario/detalle.html", context)

我相信您在表单上没有看到任何验证错误,因为对于 GET 请求,您没有传递任何内容。你传递给表单的唯一东西是模型实例,你在它上面 运行 form.is_valid 这是没有意义的。您根本不需要使用表格。请改用它。

def inventario_detalle_view(request, inventario):
    if request.method == "GET":
        codigo_activo = request.GET.get("buscar")
        print("[CODIGO ACTIVO]:", codigo_activo)
        try:
            activo = ActFijo.objects.get(codigo=codigo_activo) # get activo object
            activo.inventario_id = inventario # update object
            activo.save() # save changes
            print(activo)
        except ActFijo.DoesNotExist:
            # you can do anthing here
            # maybe redirect with a message..
            pass

    context = {"item": Inventario_detalle.objects.all()}
    return render(request, "inventario/detalle.html", context)