Home > OS >  Django - Not passing id from template to views
Django - Not passing id from template to views

Time:10-12

In my ToDoApp, I couldn't send the ID to my function. Not sure what mistake I'm making.

Seems my function is correct because when I tested the form action with "datechange/1". It worked.

Here is my code:

Index.html

{% extends 'base.html' %}
{% block content %}

<h3 style = "margin-bottom: 20px"><strong>To Do List App</strong></h3>

<form method="POST" action="datechange/{{task.id}}">
    {%csrf_token%}
<ul >
{% for task in tasklist %}


<li >
    <input type='hidden' name = {{task.id}}>{{task.tasks}}
    <span >{{task.duedate}}
        <input type="date" name="datepick"/>
        <input type='submit' value = 'Update'>   
    </span>
</li>
{% endfor %}

</form>

Views.py

def index(request):
    tasklist = Task.objects.all()
    return render(request, 'index.html', {'tasklist':tasklist})

def datechange(request,id):
    # taskid = request.POST.get(id='task.id')
    # task = Task.objects.get(id=taskid)
    task = Task.objects.get(id=id)
    datepick = request.POST.get('datepick')
    task.duedate = datepick
    task.save()
    return HttpResponseRedirect(reverse('index'))

Urls.py

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index'),
    path('datechange/<int:id>',views.datechange,name='datechange'),
]

App Screenshot

CodePudding user response:

Don't use action in form like that, Django has a better behaviour for such simple forms. The view datechange is also not needed. Just put everything from that view into if request.method == "POST" like that:

def index(request):
    if request.method == "POST":
        task_id = request.POST.get("task_id")
        task = Task.objects.get(id=task_id)
        datepick = request.POST.get('datepick')
        task.duedate = datepick
        task.save()
    tasklist = Task.objects.all()
    return render(request, 'index.html', {'tasklist':tasklist})

And delete action from your form in template:

<form method="POST">
    {%csrf_token%}
    <input type="hidden" name="task_id" value="{{ task.id }}">
    ...

Submitting the form will render index again, but also will process everything in POST you have inside that view. If you just open it (GET method) it will ignore that processing opening the view in a standard way.

  • Related