Regex Url conf Django
I am trying to get the following setup up going.
Flatpages: Where all my static sites are (like: about, contact,..)
Dynamic Pages:
Here I am trying to link from one of the Flatpages to a start site:
the regex in the url conf of this startsite I tried was:
(r'^myapp/start/(\d+)/$', 'mysite.views.def_that_should_just_show_hello_world'),
In the views I had:
def def_that_should_just_show_hello_world(request):
return HttpResponse("Hello experiment world")
If I go to
/myapp/ I get 404: No FlatPage matches the given query. /myapp/start/ I get 404: No FlatPage matches the given query. /myapp/start/1 I get
Exception Type: TypeError def_that_should_just_show_hello_world takes exactly 1 开发者_如何学Pythonargument (2 given)
I thought with this setup I would get "Hello experiment world" on EVERY page.
Where did I go wrong? I dont understand the multiple sites approach in regexs. What would I have to do to print hello world on all these sites? And then, what would I have to do to display 1 image on all of these sites?
Thanks a lot for the help!
You regular expression has a matching group in it - the (\d+)
bit.
This requires one or more numeric characters to appear at the end of the url for that view. If you do not include the number at the end, this regular expression will not match the url. (url matching works like any other regular expression matching).
When you do include the number, eg. /myapp/start/1
you then have another problem. Because there is a matching group, the part of the url in the brackets will be passed as another argument to your view. Views are always passed the request as their first parameter but in this case the '1' matched by the (\d+)
is provided as a second argument. This is why you are hetting the TypeError in this case.
Django's documentation has a lot of information on how url dispatching works, read that through and see if that makes sense!
from your_app_name import views
from django.conf.urls import url
urlpatterns = [
url(r'^$',views.method_name,name ='index'),
path('admin/', admin.site.urls),
精彩评论