How to duplicate a model object using a view


(Alejandro Jourdan) #1

How can I duplicate a model object using a view, I would like to click on a button and have the object duplicated using a pk filter

I have been working in this code, but I cant get the request.produccion_id value right

view.py:

def CopiarOrden(request):
    orden = Produccion.objects.filter(pk=request.produccion_id)
    orden.pk = None
    orden.save()
    return HttpResponse("copiado")

Thanks in advance


(Vitor Freitas) #2

Your strategy of duplicating the model should work, the missing part is the sending the produccion_id to the view.

You can pass the produccion_id in two ways: via URL path or via POST using a form.

template:

<form method="post" action="/ordens/copiar/">
  {% csrf_token %}
  <input type="text" name="produccion_id">
  <button type="submit">Copiar</button>
</form>

views:

def CopiarOrden(request):
    produccion_id = request.POST['produccion_id']
    orden = Produccion.objects.filter(pk=produccion_id)
    orden.pk = None
    orden.save()
    return HttpResponse("copiado")

Via URL path you would need a URL like this:

urlpatterns = [
    path('ordens/copiar/<int:produccion_id>/', views.CopiarOrden, name='copiar_orden')
]

Then you views would be something like this:

def CopiarOrden(request, produccion_id):
    orden = Produccion.objects.filter(pk=produccion_id)
    orden.pk = None
    orden.save()
    return HttpResponse("copiado")

(Alejandro Jourdan) #3

Wow that was fast!
Thank you very very much, it worked!
I just changed “filter” to “get” in Produccion.objects.filter(pk=produccion_id)
Regards
Alejandro Jourdan


(Vitor Freitas) #4

Ah good point! I didn’t notice it was using filter instead of get :sweat_smile: