buttons linking to url

Hi

I am trying to click a button and do so i will be redirect to a page in my urls but its not working.

mainpage.html:

  <form method="post">
  {% csrf_token %}

<input type="submit" name='mybtn1' onclick="location.href='{% url 'first-page' %}'" 
value="Make new prayer record"></input>
<br/><br/>
<input type="submit" name="mybtn2" onclick="location.href='{% url 'reporting' %}'" 
value="View prayer record report"></input>

</form>

and below are my pages in view

def mainpage(request):
	return render(request,'mainpage.html',{})

def reporting(request):
	return render(request,'reporting.html',{})

def firstpage(request):

	now = datetime.now()
	the_time = int(now.hour)
	the_date = datetime.today().strftime('%Y-%m-%d')

	if request.method=="POST":
		
		form = PrayerForm(request.POST or None, request.FILES or None)
		
		if form.is_valid():

			# add logic to code
			form.save()
			return redirect('first-page')
	
	else:
		
		form = PrayerForm()
		
	return render(request, 'prayers.html', {'the_date':the_date, 'the_time':the_time, 'form':form})

my urls:

urlpatterns = [
    path('', views.mainpage, name="mainpage"),
    path('prayers/', views.firstpage, name="first-page"),
    path('reporting/', views.reporting, name="reporting"),

]

Thanks

When I try this (hand coding it in the developer tools) this works fine. So my first recommendation would be to examine the html that gets rendered in the browser to ensure that it’s being rendered correctly. Verify that the onclick attribute is being rendered correctly.

What I do see (but am not directly aware of any adverse implications) is that you have these buttons defined as type="submit", when they are explicitly not going to submit the form in which they are enclosed. I would also recommend changing them to type="button". (Or, replace the input elements with button elements.)

1 Like