0

I met a problem when I learn Django1.11.5(python2.7) as a beginner. There are urls.py, views.py and so on. Here is views.py:

## views.py
from django.http import HttpResponse
import datetime

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

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

And here is urls.py:

## urls.py
from django.conf.urls import url
from django.contrib import admin

from mysite import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', views.hello),            ##name='home' is not necessary
    url(r'^time/$', views.current_datetime),
]

When I used the command: python manage.py runserver, there is a mistake displayed: html = "It is now %s." % now

IndentationError:unexpected indent. I checked space and and tab and coundn't find mistakes. If I change the line "now = datetime.datetime.now()" to "now = 1234", there will be no mistake. Also I found if the last line includes parenthesis, the next line will have IndentationError(Even for functions like round(2.5)).

I cannot figure this problem out, can anybody help me? Thank you very much!!!

1
  • Are you sure your editor is not using tabs for indentation or something like that? That can mess up python parser. Commented Sep 19, 2017 at 1:18

2 Answers 2

1

IndentationError: expected an indented block Python uses indentation to define blocks.

html = "<html><body>It is now %s.</body></html>" % now

I guess you use sublime text and your code is not proper indented. You can remove space from the line and write 1 tab or 4 space again.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! The problem is exactly what you pointed out.
0

Wrap the line html = "<html><body>It is now %s.</body></html>" % now with brackets.

Like this:

html = ("<html><body>It is now %s.</body></html>" % now)

A newer way of doing this would be:

"<html><body>It is now {}.</body></html>".format(now)

1 Comment

Could you explain for midudu as part of this answer why this works?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.