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

I am confused when I try to insert record from a "GET" request

I will try to explain what I want to do.

I am creating an application to take inventory of assets.

I have 3 tables in my database.

I have a main table called fixed asset("ActFijo") where all the assets of my company are registered.

Another call Inventory ("Inventario"), which stores the name of each inventory

and another call Inventory_detail ("Inventario_detalle"), where the details or assets in which they are being counted are stored to verify that the equipament or furniture is not being stolen in that location.

From the main table ("ActFijo") I have to search for the furniture or asset and store it in the detail table ("Inventario_detalle")

I'm confused I don't know how to work on a GET request and then do a POST all in one request

Do I have to write my code in parts in a GET request and then POST? Or can I do everything in the GET request?

This is the code I have so far I don't know if it's ok, please I need guidance

For example my code does not pass the validation of the form.

if form.is_valid():

I am trying to print, But I don't see any validation error, it doesn't print anything

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 %}

The problem is here

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)


Solution 1:[1]

I believe you don't see any validation errors on the form because for the GET request, you are not passing in anything. The only thing you're passing into the form is the model instance and you're running form.is_valid on it which does not make sense. You dont need to use the form at all. Use this instead.

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mess