bsky
bsky

Reputation: 20222

Server doesn't start in hello world app

I am trying to create a Django hello world app.

I have the following code:

import sys

from django.conf import settings
from django.http import HttpResponse

settings.configure(
    DEBUG=True,
    SECRET_KEY='badkey',
    ROOT_URLCONF=sys.modules[__name__],
)

def index(request):
    return HttpResponse('Hello, World')

urlpatterns = [
    (r'^hello-world/$', index),
]

Located at /smartQuiz/smartQuiz/hello.py, where smartQuiz is the root directory of my project.

If I run python hello.py runserver from the directory where hello.py is located, the server won't start.

What am I doing wrong?

Upvotes: 1

Views: 129

Answers (3)

Alex
Alex

Reputation: 6037

You seem to be missing

 from django.conf.urls import url

Here is a full minimal example previously written by minigunnr on the Stack Overflow documentation:

This example shows you a minimal way to create a Hello World page in Django. This will help you realize that the django-admin startproject example command basically creates a bunch of folders and files and that you don't necessarily need that structure to run your project.

  1. Create a file called file.py.

  2. Copy and paste the following code in that file.

    import sys
    
    from django.conf import settings
    
    settings.configure(
        DEBUG=True,
        SECRET_KEY='thisisthesecretkey',
        ROOT_URLCONF=__name__,
        MIDDLEWARE_CLASSES=(
            'django.middleware.common.CommonMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.middleware.clickjacking.XFrameOptionsMiddleware',
        ),
    )
    
    from django.conf.urls import url
    from django.http import HttpResponse
    
    # Your code goes below this line.
    
    def index(request):
        return HttpResponse('Hello, World!')
    
    urlpatterns = [
        url(r'^$', index),
    ]
    
    # Your code goes above this line
    
    if __name__ == "__main__":
        from django.core.management import execute_from_command_line
    
        execute_from_command_line(sys.argv)
    
  3. Go to the terminal and run the file with this command python file.py runserver.

  4. Open your browser and go to 127.0.0.1:8000.

Upvotes: 2

Tarun Gupta
Tarun Gupta

Reputation: 504

I think you are doing it the wrong way. Use this link to know how to make a django app

Upvotes: 0

mrmick
mrmick

Reputation: 79

I see that you are trying to directly call hello.py with runserver as an argument. If you are writing and trying to test Django, make sure that you are using the framework to start the server. It will take care of all the 'Django stuff' required: python manage.py runserver manage.py takes care of setting things up for you.

Upvotes: 1

Related Questions