pycod333
pycod333

Reputation: 764

Django url not finding a template using CreateView in Class-Based Views

I have created a page where a user can add a new item (notes in this case) and I am making use of CBV which I have recently started learning.

This is my model form

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

This is the view in views.py

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

Then this is the url as I used in the urls.py of the app

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"),

 )

NB: I used the same url as the main page at 127.0.0.1:8000 in the projects urls.py file and it worked.

I have seen several tutorials and even the docs and can't seem to find what I am doing wrong. Will I also need to add a function in order for it to be saved in the db or the CBV will do it all?

EDit: The error I get is this

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/notes/add/

Here is the project's 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
)

Upvotes: 1

Views: 1972

Answers (1)

Pynchia
Pynchia

Reputation: 11590

you say that is the urls.py of the app, which means it is included by the project's urls.py.

As you show now, all the app's URIs go under the notes prefix:

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

so as things stand at present the correct URI for the page is

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

In order to clean things up a bit, I'd suggest to modify the app's urls.py to

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

so that the page can be reached at

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

This way all the app's pages/services are available under the notes prefix and with a simple name that is consistent with their action (i.e. add, delete, etc)

Upvotes: 1

Related Questions