Where should i put the instance in django?

I am modifying a table with stored procedures, I made an instance but I need to call it inside the request, where should I put the instance?

def modificartarea(request, id):

tarea = get_object_or_404(Tarea, id=id)

data = {
    'tarea': CrearTareaForm(instance=tarea)
}

if request.method=="POST":
    if request.POST.get('nombre') and request.POST.get('descripcion') and request.POST.get('inicio') and request.POST.get('termino') and request.POST.get('repetible') and request.POST.get('activo') and request.POST.get('estado') and request.POST.get('creador') and request.POST.get('tarea_anterior'):
        tareaupdate= Tarea()
        tareaupdate.nombre=request.POST.get('nombre')
        tareaupdate.descripcion=request.POST.get('descripcion')
        tareaupdate.inicio=request.POST.get('inicio')
        tareaupdate.termino=request.POST.get('termino')
        tareaupdate.repetible=request.POST.get('repetible')
        tareaupdate.activo=request.POST.get('activo')
        tareaupdate.estado=EstadoTarea.objects.get(pk=(request.POST.get('estado')))
        tareaupdate.creador=Empleado.objects.get(rut=(request.POST.get('creador')))
        tareaupdate.tarea_anterior=Tarea(pk=(request.POST.get('tarea_anterior')))
        cursor=connection.cursor()
        cursor.execute("call SP_modificar_tarea('"+tareaupdate.nombre+"','"+tareaupdate.descripcion+"', '"+tareaupdate.inicio+"', '"+tareaupdate.termino+"', '"+tareaupdate.repetible+"', '"+tareaupdate.activo+"', '"+str(tareaupdate.estado.id)+"', '"+str(tareaupdate.creador.rut)+"', '"+str(tareaupdate.tarea_anterior.id)+"')")
        messages.success(request, "La tarea "+tareaupdate.nombre+" se edito correctamente ")

        return render(request, 'app/modificartarea.html', data)
else:
    return render(request, 'app/modificartarea.html', data)

You'd most likely like to filter it out based on something from the post request that is unique (a pk or id maybe). If not, just put your if statements inside the querysearch and then use it on the form. I assume you already have the id based on your function so you should try something like:

tarea = Tarea.objects.get(pk=id)
tareaupdate = ClearTareaForm(request.POST, instance=tarea)

Also, you don't have to use so many if cases if you need every field from your model. You can exclude the fields you dont want with exclude = ['nombre', 'inicio'] in your form's Meta class.

Back to Top