Django 缩进错误

2 投票
2 回答
15081 浏览
提问于 2025-04-15 20:12

我刚开始学习Django,正在按照一个教程写代码。但是现在我遇到了一个错误,导致我的程序无法运行:

IndentationError at /
('unexpected indent', ('D:\\django_workspace\\django_bookmarks\\..\\django_bookmarks\\bookmarks\\views.py', 14, 4, '    return HttpResponse(output)\n'))
Request Method: GET
Request URL:    http://localhost:8000/
Exception Type: IndentationError
Exception Value:    
('unexpected indent', ('D:\\django_workspace\\django_bookmarks\\..\\django_bookmarks\\bookmarks\\views.py', 14, 4, '    return HttpResponse(output)\n'))
Exception Location: D:\django_workspace\django_bookmarks\..\django_bookmarks\urls.py in <module>, line 2
Python Executable:  C:\Python26\python.exe
Python Version: 2.6.4
Python Path:    ['D:\\django_workspace\\django_bookmarks', 'C:\\Python26', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26\\lib\\site-packages']
Server time:    Tue, 9 Mar 2010 19:18:32 +

我的views.py文件的代码是:

from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
from django.template import Context
from django.template.loader import get_template

def main_page(request):
    template = get_template('main_page.html')
    variables = Context({
        'head_title': 'Django Bookmarks',
        'page_title': 'Welcome to Django Bookmarks',
        'page_body': 'Where you can store and share bookmarks!'
})
output = template.render(variables)
    return HttpResponse(output)

def user_page(request, username):
    try:
        user = User.objects.get(username=username)
    except:
        raise Http404('Requested user not found.')
        bookmarks = user.bookmark_set.all()
        template = get_template('user_page.html')
        variables = Context({
                'username': username,
                'bookmarks': bookmarks
})
output = template.render(variables)
    return HttpResponse(output)

请帮我解决这个问题!提前谢谢你。

2 个回答

-1

首先找到出现这个错误的那一行。把这一行完全删除。然后去到前一行的末尾,按一下回车键。现在再输入这一行。

14

你很可能是把制表符和空格搞混了——在缩进的时候只用其中一种...最好使用空格,具体可以参考这个:

http://www.python.org/dev/peps/pep-0008/

撰写回答