I'm doing the update function but I get a message Page not found
views.py
def detalle_tarea(request, tarea_id):
if request.method == 'GET':
tarea = get_object_or_404(Tarea, pk=tarea_id)
form = TareaForm(instance=tarea)
return render(request, 'tarea_detalles.html',
{'tarea': tarea, 'form': form})
else:
tarea = get_object_or_404(Tarea, pk=tarea_id)
form = TareaForm(request.POST, instance=tarea)
form.save()
return redirect('tareas')
url.py
from django.contrib import admin
from django.urls import path
from tareas import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.inicio, name='inicio'),
path('registrar/', views.registrar, name='registrar'),
path('tareas/', views.tareas, name='tareas'),
path('tareas/crear/', views.crear_tarea, name='crear_tarea'),
path('tareas/<int:tarea_id>/', views.detalle_tarea, name='detalle_tarea')
]
Any suggestion ???
The error from your screenshot is most likely occurring because you have incorrectly specified the action
in <form>
in your HTML template.
But aside from this error, there are a few other unclear points in your code that should be addressed.
First, duplication is unnecessary – it's simply pointless. Secondly, you are not validating the form and immediately starting to save it – this can also lead to unpleasant consequences.
I would rewrite your view function like this:
def detalle_tarea(request, tarea_id):
# eliminating duplication
tarea = get_object_or_404(Tarea, pk=tarea_id)
if request.method == 'GET':
form = TareaForm(instance=tarea)
return render(request, 'tarea_detalles.html',
{'tarea': tarea, 'form': form})
else:
form = TareaForm(request.POST, instance=tarea)
if form.is_valid():
form.save()
return redirect('tareas')
else:
# for example
messages.error(request, "Validation error")
I also recommend using print
or logging
for debugging, so you can understand if you're actually hitting your view function and what tarea_id
you're getting.
For example:
def detalle_tarea(request, tarea_id):
print(f'{tarea_id=}')