Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the first "hello world" example in the django book not working?

I am (trying) to learn Django for python 2.7 by follow the Django book, but am still stuck with the hello world example when trying to configure views.py and urls.py. I've basically copied everything line by line, but still get the same 404-error when I access the local test-server:

Request Method:     GET
Request URL:    http://127.0.0.1:8000/

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

    ^hello/$

The current URL, , didn't match any of these.

My code in views.py looks like this:

from django.http import HttpResponse

def hello(request):
     return HttpResponse("Hello world")

And urls.py:

from django.conf.urls import patterns, include, url
from mysite.views import hello

urlpatterns = patterns('',
                       url('^hello/$', hello)
                       )

When I only use "^$" for the first regex argument in the url() function it works. But whenever I try to match it with a regular expression, like the one above, which should match the HttpResponse in hello() it never works. I've tried countless of variations of hello without success. I might also add that I've tried it on both Linux and Windows. What can be a possible origin of this problem?

like image 535
Perry Avatar asked Nov 17 '25 17:11

Perry


2 Answers

The reason for 404 is that there is no matching regex for http://127.0.0.1:8000/ page in your urlpatterns:

urlpatterns = patterns('',
                       url('^hello/$', hello)
                       )

^hello/$ regex matches only http://127.0.0.1:8000/hello/ url.

like image 90
alecxe Avatar answered Nov 20 '25 08:11

alecxe


You're defining a URL for /hello but you aren't actually going to that URL, you're going to /. You need to actually use the "hello" in your browser's address bar.

like image 40
Daniel Roseman Avatar answered Nov 20 '25 06:11

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!