使用完整网址找不到Django页面

时间:2015-05-10 20:48:55

标签: python django views http-status-code-404

我是Django的新手,我正在尝试编写一个非常简单的应用程序,但是我遇到了困难并且有几个问题:

首先,我的应用程序被称为" empleados" (西班牙语),我正在尝试创建一个简单的索引视图,显示我的表中的所有条目,我可以通过localhost:8000 / empleados访问该网页,但我无法通过localhost访问该网页:8000 / empleados / index.html它不应该是一样的吗?

我当前的文件夹树是这样的:

 project_root/
  empleados/
    __init__.py
    admin.py
    forms.py
    models.py
    tests.py
    urls.py
    views.py
    templates/
      empleados/
        index.html
        add_checklist.html

  project/
    __init__.py
    settings.py
    urls.py
    views.py
    wsgi.py

我的项目/ urls.py是这样的:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    # Examples:
    # url(r'^$', 'femsa.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^empleados/', include('empleados.urls')),
    url(r'^admin/', include(admin.site.urls)),
]

empleados / urls.py看起来像这样:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^$', views.add_checklist, name='add_checklist'),
]

最后我的empleados / views.py看起来像这样:

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Empleado
from empleados.forms import *
def index(request):
    empleado_list = Empleado.objects.all()
    context = {'empleado_list': empleado_list}
    return render(request, 'empleados/index.html', context)
# Create your views here.

def add_checklist(request):
    # Get the context from the request.
    context = RequestContext(request)

    # A HTTP POST?
    if request.method == 'POST':
        form = CheckListForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            form.save(commit=True)

            # Now call the index() view.
            # The user will be shown the homepage.
            return index(request)
        else:
            # The supplied form contained errors - just print them to the terminal.
            print (form.errors)
    else:
        # If the request was not a POST, display the form to enter details.
        form = CheckListForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render_to_response('empleados/add_checklist.html', {'form': form}, context)

所以我的问题是如何使用完整的url和add_checklist.html访问index.html,每次我尝试访问它们时我都会收到404错误,提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

与其他一些框架/服务器不同,django不会自动提供文件。您必须明确指定要提供的内容。

在您的情况下,将index.html添加到url可以解决问题:

url(r'^index.html$', views.index, name='index'),
url(r'^new$', views.add_checklist, name='add_checklist'),

我必须补充一点,使用index.html是一个废弃的约定。 Django允许以更好的方式设计网址结构。看看this示例。