Django Tutorial "Write Views That Actually Do Something" - python

I've been working on the Django tutorial. I'm on the part where it is "Write Views That Actually Do something." (Part 3)
I'm trying to use the index.html template that it gives you, but I keep getting a 404 error that says
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/index.html
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/ ^$ [name='index']
^polls/ ^(?P<question_id>\d+)/$ [name='detail']
^polls/ ^(?P<question_id>\d+)/results/$ [name='results']
^polls/ ^(?P<question_id>\d+)/vote/$ [name='vote']
^admin/
The current URL, polls/index.html, didn't match any of these.
I don't know if one of the regex are wrong? I've been messing around with it for a while now and I have had no luck getting it to work.
I can go to /polls just fine. But /polls/index.html does not work.
Any help would be appreciated.
The version of Django that I'm using is 1.7.4

Django view functions or classes use the template you define, so that you do not have to specify it in the URL. The urls.py file matches your defined regex to send requests to views.
If you truly wanted to use that URL, you would have to define ^polls/index.html$ in your urls.py and direct it to your view.

From what you're asking it sounds like you essentially want to output a static html file on a URL defined in your urlpatterns in urls.py.
I strongly suggest you take a look at Class Based Views.
https://docs.djangoproject.com/en/1.7/topics/class-based-views/#simple-usage-in-your-urlconf
The quickest way to go from what you've got, to rendering polls/index.html would be something like;
# some_app/urls.py
from django.conf.urls import patterns
from django.views.generic import TemplateView
urlpatterns = patterns('',
(r'^polls/index.html', TemplateView.as_view(template_name="index.html")),
)
But I'm sure you'll want to pass things to the template so class based views will be what you need. So the alternative to the above with added context would be;
# some_app/views.py
from django.views.generic import TemplateView
class Index(TemplateView):
template_name = "index.html"
def get_context_data(self, **kwargs):
context = super(Index, self).get_context_data(**kwargs)
context['foo'] = 'bar'
return context
Then obviously adding {{ foo }} to your index.html would output bar to the user. And you'd update your urls.py to;
# some_app/urls.py
from django.conf.urls import patterns
from .views import Index
urlpatterns = patterns(
'',
(r'^polls/index.html', Index.as_view()),
)

Related

Django routing - The empty path did not match any of these

Using the URLconf defined in pccb_model.urls, Django tried these URL patterns, in this order:
predictive/
admin/
The empty path didn't match any of these.
That's correct, you need to define a view for a default path in your pccb_model.urls module. Make sure you have a corresponding method in the views.py. For example:
urls.py
path('', views.index)
views.py
def index(request):
return HttpResponse('test', status=200)

Django: - NoReverseMatch error

I'm following the djangoforgirls.org tutorial on making my first django site. I'm trying the stage "extending your template" to make a link to an article within my website that uses the general template.
I keep get thrown the error: "NoReverseMatch at /, Reverse for 'post_detail' with arguments '()' and keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P\d+)/$']"
Some variable and file names may seem strange, the use of the website was music sampling but I used the tutorial's names for things in case that was what was wrong.
My urls.py for entire project:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('sample.urls')),
]
My urls.py for the specific app (sample):
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
My views.py for the app:
from django.utils import timezone
from .models import AudioSample
from django.shortcuts import render, get_object_or_404
def post_list(request):
samples = AudioSample.objects.order_by('length')
return render(request, 'blog/post_list.html', {'samples': samples})
def post_detail(request, pk):
post = get_object_or_404(AudioSample, pk=pk)
return render(request, 'blog/post.html', {'post': post})
And the line of code from the base template that's the link to another page in the website:
How to sample
I saw another person that asked this question with a similar project here and got it fixed but I dont understand the answer enough to make the change to mine (I dont understand what the namespace is).
If you have more than one urls.py, namespace can tell django how to handle the request. So in normally, namespace is the APP name.
In your project urls.py, try replacing r'' with r'^'. The former matches all urls, while the latter matches the start of the string.

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

How to redirect url pattern with variables from urls.py in Django?

I'd like to redirect url pattern with variables from urls.py.
I refer other stackoverflow solution, but I don't know when url having a variable like following code.
from django.conf.urls import patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
url(
r'^permalink/(?P<id>\d+)/foo/$',
RedirectView.as_view(url='/permalink/(?P<id>\d+)/')
),
)
With this code, django will redirect /permalink/1/foo/ to /permalink/(?P<id>\d+)/, not the /permalink/1/.
Is there any solution without using views.py?
Of course I know solution using controller, but I wonder is there any simpler solution with using url pattern.
Passing url='/permalink/(?P<id>\d+)/' to RedirectView will not work, because the view does not substitute the named arguments in the url.
However, RedirectView lets you provide the pattern_name instead of the url to redirect to. The url is reversed using the same args and kwargs that were passed for the original view.
This will work in your case, because both url patterns have one named argument, id.
urlpatterns = [
url(r'^permalink/(?P<id>\d+)/foo/$',
RedirectView.as_view(pattern_name="target_view"),
name="original_view"),
url(r'^permalink/(?P<id>\d+)/$', views.permalink, name="target_view"),
]
If the target url pattern uses other arguments, then you can't use url or pattern_name. Instead, you can subclass RedirectView and override get_redirect_url.
from django.core.urlresolvers import reverse
from django.views.generic import RedirectView
class QuerystringRedirect(RedirectView):
"""
Used to redirect to remove GET parameters from url
e.g. /permalink/?id=10 to /permalink/10/
"""
def get_redirect_url(self):
if 'id' in self.request.GET:
return reverse('target_view', args=(self.request.GET['id'],))
else:
raise Http404()
It would be good practice to put QuerystringRedirect in your views module. You would then add the view to your url patterns with something like:
urlpatterns = [
url(r'^permalink/$', views.QuerystringRedirect.as_view(), name="original_view"),
url(r'^permalink/(?P<id>\d+)/$', views.permalink, name="target_view"),
]

Handling Multiple Views/ Multiple Urls in Django

I'm having the 404 error when trying to handle a view that is not related to the main page. For example, if I initially start at the main page home, and want to navigate to another page called, otherpage, I receive a 404 otherpage.html not found.
The way I'm doing is based off intuition. So if there's a better way to do this, please mention it:
in the file:
prd/
views.py
url.py
otherstuffthatshouldbehere.py..
I have views.py (this is where I think the error is):
from django.shortcuts import render
def home(request):
context = {}
template = "index.html"
return render(request, template, context)
def otherpage(request):
context = {}
template = "otherpage.html"
return render(request, template, context)
Then urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'prd.views.home', name='home'),
url(r'^$', 'prd.views.otherpage', name='otherpage'),
url(r'^admin/', include(admin.site.urls)),
)
This returns a 404 for the otherpage.html. I have the template directory working fine. But how do I go about handling multiple views?
EDIT:
Upon adding:
url(r'^otherpage$', 'prd.views.otherpage', name='otherpage'),
I received this error:
Using the URLconf defined in prd.urls, Django tried these URL patterns, in this order:
^$ [name='home']
^about$ [name='about']
^projects$ [name='projects']
^admin/
The current URL, about.html, didn't match any of these.
The urlpatterns starts at the top and then goes down until it matches a URL based on the regex. In order for Django to serve up the page located at otherpage.html there has to be a URL defined in urlpatterns that matches otherpage.html otherwise you will get the 404.
In this case you have:
url(r'^$', 'prd.views.home', name='home'),
url(r'^$', 'prd.views.otherpage', name='otherpage'),
Note that nothing will ever get to otherpage here because home has the same pattern (regex) and will therefore always match first. You want to have a different URL for both those so that you can differentiate between them. Perhaps you could do something like:
url(r'^$', 'prd.views.home', name='home'),
url(r'^otherpage.html$', 'prd.views.otherpage', name='otherpage'),
After making this change you now have a match for otherpage and hopefully no more 404.
EDIT:
url(r'^otherpage.html$', 'prd.views.otherpage', name='otherpage'),
This matches www.example.com/otherpage.html but it will not match www.example.com/otherpage
To match www.example.com/otherpage you need to use:
url(r'^otherpage$', 'prd.views.otherpage', name='otherpage'),
Note the difference in the regex, there's no .html here. The regex matches exactly what you put in it.

Categories

Resources