Python Django代码的IndentationError?

时间:2017-09-19 01:13:12

标签: python django python-2.7

当我作为初学者学习Django1.11.5(python2.7)时,我遇到了一个问题。有urls.py,views.py等。这是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)

这是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),
]

当我使用命令:python manage.py runserver时,显示错误:     html =“现在是%s。” %now

IndentationError:意外缩进。我检查了空间和标签,但没有发现错误。如果我将“now = datetime.datetime.now()”行更改为“now = 1234”,则不会有错误。另外我发现如果最后一行包括括号,下一行将有IndentationError(即使是圆形(2.5)等函数)。

我无法解决这个问题,有人能帮助我吗? 非常感谢!!!

2 个答案:

答案 0 :(得分:1)

IndentationError:预期缩进块Python使用缩进来定义块。

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

我猜你使用了崇高的文字而且你的代码没有正确缩进。您可以从行中删除空格并再次写入1个标签或4个空格。

答案 1 :(得分:0)

用括号括起行html = "<html><body>It is now %s.</body></html>" % now

像这样:

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

更新的方法是:

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