1

I'm trying to make a basic function in Django, but I don't know how to call the function in views.py from the template when a button is clicked. I did find a similar question here. But actionUrl confused me a lot, and I am not sure how to implement it.

Button code in template:

<form action ="{% check1 %}"  method = "POST">
    {% csrf_token %}
    <button type='submit'> True</button>
</form>

Currently I have commented out the actual logic of the function and am just trying to get it to respond so it's here:

def check1(request):
  return HttpResponse("why u no work")

urls.py:

urlpatterns = [
 path('', Posts, name='Posts'),
 path('', index, name = 'index'),
 path('', check1, name = 'check1'),
 #path(actionUrl, views.check1),
]
montrealist
  • 5,593
  • 12
  • 46
  • 68
masha
  • 19
  • 2
  • Should be `action ="{%url 'check1' %}"` I think – Robin Zigmond Mar 10 '19 at 18:43
  • Oh, except that you have 3 identical URL patterns. That's not going to work, because Django is going to stop on the first match. (Surprised there isn't any kind of warning for this.) – Robin Zigmond Mar 10 '19 at 18:44
  • Oh, right. any ideas where to learn to fix that? I'll try searching, thanks! – masha Mar 10 '19 at 18:59
  • Not sure what you mean by "learn to fix that". Quite simply, those 3 different view functions should correspond to 3 different URLs. – Robin Zigmond Mar 10 '19 at 19:18
  • from game.views import index I thought doing the import would assign them. I'm just going to not make it a button and hope for the best. – masha Mar 10 '19 at 19:27
  • You seem to be missing the key point. When a request comes in to a particular URL, the very first thing Django does is look up that URL in the URL patterns you've provided, and (assuming it finds it) passes the request object to the corresponding view function. So when there is a request to the URL `''` (that's the application root, unless this is an included URLconf), Django will look at your list and see you've mapped it to the `Posts` view. It won't get to `check1`, because it's already found a match. Each URL should map to at most one view function. – Robin Zigmond Mar 10 '19 at 19:37
  • Okay, yes you're right about me not seeing the key point then, thanks! That really helped. – masha Mar 11 '19 at 10:35

0 Answers0