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.
Related
I'm learning Chapter 18 in Python Crash Course by Eric Matthes. I am using Django 4.0.1 and the book uses is 2.2.0 so I see that other people are having similar issues as me with this section.
In other similar stackoverflow questions on this issue, proposed solutions using url instead of path seem also outdated. The solutions on the website therefore are unfortunately not helping me.
Problem:
when I open http://localhost:8000/ and I click on "topics" I get the 404 not found error as follows:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/(%25%20url%20'learning_logs:topics'%20%25%7D
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
topics/ [name='topics']
The current path, (% url 'learning_logs:topics' %}, didn’t match any of these.
However, navigating manually to http://localhost:8000/topics shows me the page as intended. I believe this is an issue due to my urls.py located in my app folder.
Here is my urls.py in learning_logs (app), where I think the issue lies:
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
#Home page
path('', views.index, name='index'),
#Page that shows all topics.
path('topics/', views.topics, name='topics'),
]
Here is my urls.py in learning_log (main project):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('learning_logs.urls')),
]
views.py
from django.shortcuts import render
from .models import Topic
# Create your views here.
def index(request):
"""The home page for Learning Log."""
return render(request, 'learning_logs/index.html')
def topics(request):
"""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context)
base.html found in template/learning_logs folder:
<p>
<a href="{% url 'learning_logs:index' %}" >Learning Log</a> -
<a href="(% url 'learning_logs:topics' %}" >Topics</a>
</p>
{% block content %} {% endblock content %}
topics.html
{% extends "learning_logs/base.html" %}
{% block content %}
<p> Topics </p>
<ul>
{% for topic in topics %}
<li> {{topic}}</li>
{% empty %}
<li> No topics have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}
and finally index.html:
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Learning Log helps you keep track of your learning, for any topic you're
learning about.</p>
{% endblock content %}
The comment below my question by Willem Van Onsem answered my question, turns out it was a typo.
The Topics did not start the url template tagb with {%... –
Willem Van Onsem
How do I use the {% url .. %} template tag in a "library" app to create a link to the library-app's own views?
Given a site with mysite/urls.py:
urlpatterns = [
url(r'^myapp/', include('myapp.urls', namespace='mysite')),
]
and an app with myapp/urls.py:
urlpatterns = [
url(r'^mylib/', include('mylib.urls', namespace='mylib')),
]
and the library app with mylib/urls.py:
urlpatterns = [
url(r'^commands/$', views.commands, name='list-commands'),
url(r'^command-1/$', views.command_1, name='command-1'),
]
where the views.commands view displays a template that should contain a link to /myapp/mylib/command-1/, ie. mylib/templates/mylib/list-commands.html
<a href='{% url "command-1" %}'>command-1</a>
It will of course work if I change it to:
{% url "mysite:mylib:command-1" %}
but the author of mylib doesn't know about neither mysite or myapp...?
I have a feeling I've misunderstood something basic...
in your myapps/urls add:
app_name = #enter app_name here[say x]
then use
{% url 'x:command-1' %}
read this: https://docs.djangoproject.com/en/3.1/topics/http/urls/
I have an app that is going to display some information about people in my group. I'm getting a NoReverseMatch error when trying to use the url tag in my index.html. If I do not use the url tag, but specify the root, I do not receive the error.
The error says:
NoReverseMatch at /
Reverse for 'specialist' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$(?P[0-9]+)/']
Here is are the urls.py files.
From the main wi_tech urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('person.urls')),
url(r'^tech/', include('person.urls')),
url(r'^admin/', admin.site.urls),
]
From the 'person' app urls.py:
from django.conf.urls import url
from . import views
app_name = 'person'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='specialist'),
]
My views.py file looks like this:
from django.views import generic
from .models import Specialist
class IndexView(generic.ListView):
template_name = 'person/index.html'
context_object_name = 'person_list'
def get_queryset(self):
"""Return all specialists"""
return Specialist.objects.order_by('id')
class DetailView(generic.DetailView):
model = Specialist
template_name = 'person/detail.html'
And my index.html page looks like this:
{% if person_list %}
<ul>
{% for specialist in person_list %}
<li> {{ specialist }}</li>
{% endfor %}
</ul>
{% else %}
<p>No specialists are available.</p>
{% endif %}
If I change my tag in index.html to this, it works:
<li> {{ specialist }}</li>
Obviously this isn't an ideal situation in case the web root ever changes. I've reviewed a lot of SO questions on this, and nothing seems to match. I think the issue is the "$" in the beginning of the regex, but I don't see where that's coming from.
Specifically, I used this link as a really good reference point, but came up empty looking through my code.
what is NoReverseMatch and how do i fix it
Clearly there's something I'm missing.
Could it be the additional / at the end of the URL?
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='specialist')
The one after your primary key modifier. When you click the URL (with the (% url ':' model.name %)) what URL comes up in your browser?
I ended up scrapping this implementation, and going with a flatter structure whereby all models, views and templates are in the same application. I have not had this problem in the new design.
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.
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>