Home > other >  Django button click gets triggered but not updating model
Django button click gets triggered but not updating model

Time:09-18

I tried to upload the image several times, for some reason it just won't upload. I will explain in detail -

This table is on my django template.It will display data from a model called "WorkOut". This page has a form above this table for manual data input. Three fields in the table are going to be dynamic, that is where the issue is. In the picture you will see the "Start Time" field that says none. I want to fill this field with a button click. Idea is to click the button, that will trigger a views.py function and that will update the model and then display on this page. Once I do this successfully I will add the end time and do some calculations after.

I added a small form in the for loop to generate the button-

<td>
            <form method="get">
            <input type="submit"  value="Start Time" name="start_time">
            </form>
        </td>

Here is the views function that it is suppose to trigger-

def index_2(request):
     
    if(request.GET.get('start_time')):
        time=datetime.now().strftime('%H:%M:%S')
        WorkOut.objects.update(start=time)


    products=WorkOut.objects.all()
    context={'products': products}
    return render(request, 'myapp/index.html', context)

This page is the index and no separate url for the button click. I don't think I need one.

Here is the main index views:

def index(request):
    form = WorkOutForm()
    if request.method == 'POST':
        form = WorkOutForm(request.POST)
        if form.is_valid():
            form.save()
            
   products=WorkOut.objects.all()
   
   context = {'form': form, 'products': products }

   return render(request, 'myapp/index.html', context)

When I click the button it seems to get triggered but the function is not doing what it is suppose to do. My localhost url changes from 127.0.0.1:8000 to http://127.0.0.1:8000/?start_time=Start Time. So something is happening but not the desired action.

Any idea what need to be changed?

Thank you for any input.

CodePudding user response:

submit button value does not submit, so add a hidden field

index view:

def index(request):
    form = WorkOutForm()
    if request.method == 'POST':
        form = WorkOutForm(request.POST)
        if form.is_valid():
            form.save()
    elif request.GET.get('start_time'):
        time=datetime.now().strftime('%H:%M:%S')
        WorkOut.objects.update(start=time)
            
   products=WorkOut.objects.all()
   
   context = {'form': form, 'products': products }

   return render(request, 'myapp/index.html', context)

form

<td>
        <form method="get">
            <input type="hidden" value="1" name="start_time">
            <input type="submit" >
        </form>
</td>
  • Related