【问题标题】:Django url not finding a template using CreateView in Class-Based ViewsDjango url 在基于类的视图中找不到使用 CreateView 的模板
【发布时间】:2015-10-28 21:49:33
【问题描述】:

我创建了一个页面,用户可以在其中添加新项目(在本例中为注释),并且我正在使用我最近开始学习的 CBV。

这是我的模型表格

class NoteForm(forms.ModelForm):
class Meta:
    model = Note
    fields = ('title', 'note', 'tags')

这是views.py中的视图

class NoteCreate(CreateView):
    model = Note
    form_class = NoteForm
    template_name = "add_note.html"

那么这是我在应用程序的 urls.py 中使用的 url

from django.conf.urls import patterns, url
from . import views
from madNotes.views import  NoteCreate, NoteIndex, 

urlpatterns = patterns(
    '',
    url(r'^notes/add/$', NoteCreate.as_view(), name="new_note"),
    url(r'^$', NoteIndex.as_view()),
    url(r'^(?P<slug>\S+)/$', views.NoteDetail.as_view(), name="entry_detail"),

 )

注意:我在项目 urls.py 文件中使用了与 127.0.0.1:8000 的主页相同的 url,并且它有效。

我看过几个教程,甚至是docs,但似乎找不到我做错了什么。我是否还需要添加一个函数才能将其保存在数据库中,或者 CBV 会完成所有工作?

编辑:我得到的错误是这样的

找不到页面 (404) 请求方法:GET 请求网址:http://127.0.0.1:8000/notes/add/

这里是项目的 urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
from MadNotez import settings
from registration.backends.default.views import RegistrationView
from madNotes.forms import ExRegistrationForm
if settings.DEBUG:
    import debug_toolbar
urlpatterns = patterns('',
    url(r'^__debug__/', include(debug_toolbar.urls)),
    url(r'accounts/register/$', RegistrationView.as_view(form_class = ExRegistrationForm), name='registration_register'),
    url(r'^accounts/', include('registration.backends.simple.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url('^markdown/', include('django_markdown.urls')),
    url('^notes/', include('madNotes.urls')),
    #url(r'^$', views.NoteCreate.as_view(), name="new note"), when I used it here it worked
)

【问题讨论】:

  • 您得到的确切错误是什么?
  • 你得到的错误是什么?您是否尝试删除 url 名称中的空格 -> 'new_note' ?
  • @Gocht 我刚刚做了,同样的错误。当我从项目的 urls.py 文件中将其设置为应用程序的默认页面时,我实际上得到了该页面,我想知道为什么它在应用程序 urls.py 中不起作用
  • @Gocht 这也是我的第一个想法,但我只是在我自己的项目中尝试了一个带有空格的 url 名称,它的工作方式很奇怪。看来 Django 对 url 名称没有那么严格。
  • 同一个文件中定义的 url 是否比这个多?它们工作正常吗?

标签: python django


【解决方案1】:

你说的是appurls.py,也就是说它包含在项目的urls.py中。

正如您现在所展示的,所有应用的 URI 都位于 notes 前缀下:

url('^notes/', include('madNotes.urls')),

就目前而言,页面的正确 URI 是

http://127.0.0.1:8000/notes/notes/add/

为了稍微清理一下,我建议将应用程序的urls.py 修改为

url(r'^add/$', NoteCreate.as_view(), name="new_note"),

这样页面就可以到达

http://127.0.0.1:8000/notes/add/

这样,应用程序的所有页面/服务都可以在 notes 前缀下使用,并使用与其操作一致的简单名称(即adddelete 等)

【讨论】:

  • 哇...工作!谢谢。我很想清理它并改为 /notes/add 。我要删除什么才能做到这一点?
  • 很高兴为您提供帮助。查看答案:)
猜你喜欢
  • 2014-01-22
  • 2019-06-13
  • 2018-04-13
  • 2012-03-11
  • 2015-07-26
  • 1970-01-01
  • 2021-07-12
  • 2015-08-10
  • 2020-05-17
相关资源
最近更新 更多