midudu
midudu

Reputation: 171

An IndentationError of Python Django code?

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!!!

Upvotes: 0

Views: 286

Answers (2)

Shaon shaonty
Shaon shaonty

Reputation: 1415

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.

Upvotes: 1

Kyle Higginson
Kyle Higginson

Reputation: 942

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)

Upvotes: 0

Related Questions