0

I'm having trouble with the Django URL-View system. I've been trying out a view:

#views.py...
def IsolatedForm(request, lat, lng, slug):
    if not request.user.is_authenticated():
        return redirect('login')
    chosen_form = Form.objects.filter(slug=slug)
    return render(request, 'polls/isolatedform.html', {'chosen_form':chosen_form, 'lng': lng, 'lat': lat})

I've associated it with a URL pattern that takes a couple of floats (coordinate values) and a slug:

#urls.py...
url(r'^testing/(-?\d+\.\d+),(-?\d+\.\d+)/(?P<slug>.*)/$', views.IsolatedForm, name='isolatedform'),

When I try this URL pattern with, for example (with the App name being polls):

polls/testing/1.0,-1.0/postchaos/

(where "postchaos" is an example slug that corresponds to an existing Form) I get:

TypeError at /polls/testing/1.0,-1.0/postchaos/ IsolatedForm() takes exactly 4 arguments (2 given)

I'm not being able to realize what the actual issue is, as the URL I've tried contains the expected numbers and the expected slug. Any help would be appreciated.

S_alj
  • 447
  • 1
  • 3
  • 15

2 Answers2

1

You have to name the variables. The URL can't understand the "lat" and "lng" vars, so they can't be passed to the view. Try correcting them, for example:

url(r'^testing/(?P<lat>\w+)/(?P<lng>\w+)/(?P<slug>.*)/$', views.IsolatedForm, name='isolatedform'),

Remember that all captured parameters are always strings, you should validate them in the view.

jgmh
  • 639
  • 10
  • 22
  • This does not solve the issue. And I'm not sure about having to name the variables like that. In another view with a similar, but simpler URL without the slug, I can get the coordinates as arguments fine. – S_alj Jun 13 '17 at 01:13
  • Did you change the comma (",") for a slash ("/")? – jgmh Jun 13 '17 at 01:25
  • I ended up finding a way to solve my problem that doesn't need a slash there, or to just allow every argument to be a string like that URL pattern you wrote. I'm giving you my upvote though, as your "naming the variables" tip helped and was actually the core of this issue. Thanks – S_alj Jun 13 '17 at 02:27
0

Meanwhile I've found a couple of other answers here on Stack Overflow that made it possible to solve the problem while also restricting the lat/lng arguments to floats that are separated by a comma:

Naming the float-like arguments: https://stackoverflow.com/a/1128740/6857994

And a better RegEX for the slug: https://stackoverflow.com/a/15080420/6857994

Here's the pattern that works:

url(r'^testing/(?P<lat>[+-]?(\d*\.)?\d+),(?P<lng>[+-]?(\d*\.)?\d+)/(?P<slug>[\w-]+)/$', views.IsolatedForm, name='isolatedform'),

Also, despite @jgmh 's answer not solving the issue for not keeping my constraints, the tip about naming the values was helpful. Thanks

Edit: RegEx change to allow signed floats

S_alj
  • 447
  • 1
  • 3
  • 15