I'm doing the Django tutorial, part 3: https://docs.djangoproject.com/en/dev/intro/tutorial03/
I currently have this text in my views.py:
from django.http import HttpResponse
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
output = ', '.join([p.question for p in latest_poll_list])
return HttpResponse(output)
This works when i go to:
http://localhost:8000/polls/, it displays the records
The problem is when I take the next step and change the views.py to:
from django.shortcuts import render
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
context = {'latest_poll_list': latest_poll_list}
return render(request, 'polls/index.html', context)
From http://localhost:8000/polls/ it shows the following error:
TemplateDoesNotExist at /polls/
From http://localhost:8000/polls/index.html it shows this error:
Page not found (404)
I have my mysite/urls.py set to:
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
I have my poll/views.py set to:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
I have my TEMPLATE_DIRS set to:
'/path/to/mysite/templates'
Why won't the page load with the new code?
You don't show the entire TEMPLATE_DIRS setting. But I suspect you have this:
TEMPLATE_DIRS = (
'/path/to/mysite/templates'
)
when you should actually have this:
TEMPLATE_DIRS = (
'/path/to/mysite/templates',
)
Note the extra comma after the end of the string. The comma is required for a single-element tuple in Python - otherwise, it's just a string in brackets.
Create a folder named polls in templates directory and create an index.html file in it with the following content.
<html>
<body>
<ul>
{% for p in latest_poll_list %}
<li>{{ p.question }}</li>
{% endfor %}
</ul>
</body>
</html>
Related
I am getting the below error when I am trying to load the home page:
Reverse for 'display_data' not found. 'display_data' is not a valid view function or pattern name
My views.py file is as follows:
def home(request):
#query_results = QRC_DB.objects.all()
return render(request, 'display_data.html')
def display_data(request,component):
#query_results = QRC_DB.objects.all()
return HttpResponse("You're looking at the component %s." % component)
My urls.py file under the app is as follows:
from django.urls import path
from fusioncharts import views
urlpatterns = [
path('home/', views.home, name=''),
]
The urls.py file under the project is as follows:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('fusioncharts.urls'))
]
And my html file (display_data) code is as follows :
{% block content %}
<h3>Display the test results</h3>
<div id="container" style="width: 75%;">
<canvas id="display-data"></canvas>
<li>SQL</li>
</div>
{% endblock %}
Can anyone please help me to find out the mistake ?
Thanks.
Your urls.py file doesn't contain any url for display_data.
When you're trying to click the link rendered in the HTML tag, namely,
<li>SQL</li>
it tries to resolve the URL display_data.
First, it checks the root urls.py file. Among the following:
path('admin/', admin.site.urls),
path('', include('fusioncharts.urls'))
it matches the second one. Then it loads the fusioncharts.urls but the fusioncharts.urls doesn't contain any URL for display_data. That's why you are getting the error.
The urls.py file should be like this:
from django.urls import path
from fusioncharts import views
urlpatterns = [
path('home/', views.home, name=''),
path('display_data/<str:arg>', views.display_data, name='display_data'),
]
# There is a change in urls.py and in your template 'display_data.html'
urls.py
urlpatterns = [
path('home/', views.home, name=''),
path('display_data/<str:component>', views.display_data, name='display_data'),
]
display_data.html
{% block content %}
<h3>Display the test results</h3>
<div id="container" style="width: 75%;">
<canvas id="display-data"></canvas>
<li>SQL</li>
</div>
{% endblock %}
Having trouble figuring out why I keep getting the NoReverseMatch.
app/url.py
from django.conf.urls import url, patterns
from . import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<contact_id>\d+)/detail/$', views.details, name='details'),
)
views.py
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.views import generic
from django.template import RequestContext, loader
from .models import Person
# Create your views here.
class IndexView(generic.ListView):
template_name = 'ContactManager/index.html'
context_object_name = 'contact_list'
def get_queryset(self):
return Person.objects.order_by('lname')
def details(request, contact_id):
contact = get_object_or_404(Person, id=contact_id)
return render(request, 'ContactManager/details.html', {'contact': contact})
# class DetailView(generic.ListView):
# model = Person
# context_object_name = 'contact'
# template_name = 'ContactManager/details.html'
#
# def get_queryset(self):
#
template index.html
{% if contact_list %}
<ul>
{% for contact in contact_list %}
<li>
{{ contact.fname }} {{ contact.lname }}
</li>
{% endfor %}
</ul>
{% else %}
<p>You don't have any contacts currently.</p>
{% endif %}
The error I am getting:
Reverse for 'details' with arguments '()' and keyword arguments '{'contact_id': 1}' not found. 1 pattern(s) tried: ['$(?P<contact_id>\\d+)/detail/$']
I have tried using generic views and a host of arguments in the {% url ... %}
Any help would be much appreciated.
I think that details url pattern has a mistake, in error message appears one tried pattern, started and ended by $ sign:
1 pattern(s) tried: ['$(?P\d+)/detail/$']
check your pattern that is equal to or no:
^(?P<contact_id>\\d+)/detail/$
if this is correct check your urls file that included contact urls and if is similar below:
url('^$', include(ContactManager.urls, namespace='contact'))
remove $ sign at end of prefix-pattern:
url('^', include(ContactManager.urls, namespace='contact'))
Note that this error can also arise if you do not define name in your urlpatterns.
Doing something like
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^error_containing_view/$', views.error_containing_view, name='error_containing_view'),
]
in your app's urls.py would fix the error.
I am getting the following error:
NoReverseMatch at /lld/new/
Reverse for 'display_lld' with arguments '()' and
keyword arguments '{'slug': u'stack-overflow-new-document'}' not found.
0 pattern(s) tried: []
I can't get to the bottom of it, though I think it has something to do with either my url regex or the document.slug variable passed to the index.html template in views.py.
views.py:
from django.shortcuts import get_object_or_404, render, redirect
from .models import Document
from .forms import DocumentForm
def index(request):
document_list = Document.objects.order_by('-date_updated')
context = {'document_list': document_list}
return render(request, 'lld/index.html', context)
def display_lld(request, slug):
document = get_object_or_404(Document, slug=slug)
return render(request, 'lld/display_lld.html', {'document': document})
def new_lld(request):
if request.method == "POST":
form = DocumentForm(request.POST)
if form.is_valid():
document = form.save(commit=False)
document.save()
return redirect('display_lld', slug=document.slug)
else:
form = DocumentForm()
return render(request, 'lld/new_lld.html', {'form': form})
site urls.py:
urlpatterns = [
url(r'^lld/', include('lld.urls', namespace="lld")),
url(r'^admin/', include(admin.site.urls)),
]
app urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
# example: /lld/
url(r'^$', views.index, name='index'),
# example: /lld/new/
url(r'^new/$', views.new_lld, name='new_lld'),
# ex: /lld/customername-projectname/
url(r'^(?P<slug>([\w-]+))/', views.display_lld, name='display_lld'),
]
index.html:
{% if document_list %}
<ul>
{% for document in document_list %}
<li>{{ document.customer }} / {{ document.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No documents are available.</p>
{% endif %}
Create New LLD
The form creates the new document fine, it shows up in the admin. But when I click on the forms save button it brings up the NoReverseMatch error rather than redirecting back to the created document. The newly created document is listed on the index page and I can navigate to it by clicking on it's link there, it just appears to throw the error in the form redirect.
When calling redirect, you have left out the lld namespace. You need to include the namespace when you use redirect or reverse, the same way as you already do when you use the {% url %} tag in your templates:
return redirect('lld:display_lld', slug=document.slug)
from django.core.urlresolvers import reverse
return redirect(reverse('lld:display_lld', args=[document.slug]))
I have a template for an about page which refuses to show. I'm probably doing something silly but I can't work out why and it's driving me insane!
part of views.py:
# About view
def about(request):
return render(request, 'blog/about.html')
urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from blog.views import post as blog_post
from blog.views import profile as blog_profile
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'blog.views.index'),
url(r'^about/$', 'blog.views.about'),
url(r'^profiles/$', 'blog.views.profile_index'),
url(r'^profiles/(?P<profile_url>[\w\-]+)/$', blog_profile, name = 'blog_profile'),
url(r'^(?P<category>[\w\-]+)/$', 'blog.views.categoryIndex'),
url(r'^(?P<category>[\w\-]+)/(?P<slug>[\w\-]+)/$', blog_post, name = 'blog_post')
)
the about template (not including the base.html):
{% extends 'base.html' %}
{% block title %} About {% endblock %}
{% block content %}
<h1>About</h1>
{% endblock %}
Using Django 1.6.5
Tried to navigate to mysite.com/about/
Template hierachy:
templates
base.html
blog
about.html
....
If your templates dir is at the root level of the project, you might want to add the following to the settings.py
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
I've figured out the problem, the following url was being matched with the about page instead:
url(r'^(?P<category>[\w\-]+)/$', 'blog.views.categoryIndex'),
Removing this solves the issue and displays the about page. This page explains about url ordering http://www.webforefront.com/django/regexpdjangourls.html
Because my about url was listed before the conflicting one, it was skipped.
I recently started to work with Django-cms. I just created two templates base.html and home.html (this latter extends base.html), registered them into settings.py like this :
CMS_TEMPLATES = (
('base.html', 'Default'),
('home.html', 'Homepage'),
)
I've created my home page within the admin and selected the Homepage template but the content of this file is never shown.
I have followed the instructions from the documentation, but I don't understand where my mistake.
Anyone has any idea ?
Did you check your urls.py?
You have to make sure that you make a regualr expression that maps your views to your url and in your views you then call/load the template.
https://docs.djangoproject.com/en/dev/intro/tutorial03/
Little example on Kyle Calica's post:
in your urls.py you add something like this: (in your myproject/ folder where also your settings.py file is)
urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
)
then in myapp.urls you need something like:
urlpatterns = patterns('',
url(r'^$', views.myview, name='myview'),
)
and then in your view:
def test(request):
return render(request, "my template.html")
and last in your template extend your base:
{% extends "base.html" %}
edit:
These are simple basics of django. if you dont grasp them i suggest you run the tutorial again and try to understand what they are actually doing.
Hi Hans (and #Kyle Calica-St), Thanks for your answer, but I have a correct urls configuration. I just created a new Blog app and I encountered the same problem. Here is my files :
settings.py
CMS_TEMPLATES = (
('base.html', 'Default'),
('home.html', 'Homepage'),
('news/home_news.html', 'News'),
)
urls.py
urlpatterns = i18n_patterns('',
# Homepage
url(r'^$', home_view),
# News
url(r'^news/', include('apps.news.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('cms.urls')),
)
views.py
def home_view(request):
return render(request, 'home.html')
home.html
{% extends "base.html" %}
{% load cms_tags %}
{% block base_content %}
{% placeholder home_content %}
<p>Hello World !</p>
{% endblock %}
Idem for news app
When I access to the homepage, I don't see the "Hello World !" p HTML tag.
I tried to change the order of the urls matches with no results.