I am brand new to Django and following along with the tutorial. I'm hoping this is just an obvious mistake, but I am unable to get my web browser to render anything written in the Django template language and I can't figure out why.
Here is my directory structure for some context: https://imgur.com/dGNIiDa
project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('budget/', include('budget.urls')),
path('admin/', admin.site.urls)
]
budget/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('<int:account_id>/', views.get_account, name='detail'),
]
budget/views.py:
from django.shortcuts import render
from django.http import HttpResponse
from budget.models import Account, Transaction
def get_account(request, account_id):
accts = Account.objects.filter(pk=account_id)
context = {"test": accts}
return render(request, 'budget/detail.html', context)
budget/templates/budget/detail.html:
<p>This is a {{ context.test }}</p>
When I visit localhost:8000/budget/1 in my browser this is all that is rendered: https://imgur.com/j2Vh0yb
Clearly Django is finding the template file and sending it to the browser, but anything that is written inside of {} does not get recognized or rendered at all. I've followed along exactly with the tutorial and I have no idea why it's not working. Any ideas?
You don't need context in the expression in the template; all that you put in the context are "globals" in the template, so try
<p>This is a {{ test }}</p>
instead.
Django's template engine has the unfortunate property of being silent about nonexisting properties, so it's hard to debug stuff like this.
Related
Django is unable to load my template because "NoReverseMatch at /books/outlines/20
"
This issue lies within a link in the template:
New Blank Outline
Here is my outlines/urls.py
from django.urls import path
from .views import Dashboard
from . import views as outline_views
urlpatterns = [
path('<int:pk>/', outlines_views.outline, name='url-outline')
path('blank/<int:storyPk>', outline_views.newBlankOutline, name='url-blankOutline'),
path('test/', outline_views.testView, name = 'test')
]
urlpatterns += staticfiles_urlpatterns()
Here is the testView:
def testView(request):
return render(request, 'outlines/test.html')
Here is the outline view:
def outline(request, pk):
context = {
'storyPk': pk
}
return render(request, 'outlines/outline.html', context)
The django error tells me:
NoReverseMatch at /books/outlines/20
Reverse for 'test' not found. 'test' is not a valid view function or pattern name.
The weird thing is, if I change the url name in the template to a url name from another app's urls.py file, it renders the template no problem. Any idea why it can't find the url?
New Blank Outline
how about try this
first of I want to apologize if I use the wrong terms or words in my question. I'm completely new to Django and got only a few months of experience with python. I hope you can understand my question anyways. I also want to acknowledge the fact that I'm using some imports that are not needed here and might not be relevant to the latest version of Django, I'm starting to get lost in all the things I've tried from other threads to solve my problem.
I'm having some problems with showing a page from apps url.
I'm getting redirected to my homepage when trying to reach localhost:8000/articles (because /articles gives 404 error)
I'm not sure exactly what code I need to include here, so bear with me.
articles/urls.py and articles/views.py
from django.conf.urls import url
from django.urls import include, path
from django.conf.urls import include, url
from django.urls import path
from .import views
urlpatterns = [
path('^$', views.article_list),
]
from django.shortcuts import render
from django.http import HttpResponse
# views
def article_list(request):
return render(request, "articles/article_list.html")
The project's urls.py and project's views.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.urls import include, path
from django.conf.urls import include, url
from django.urls import path, re_path
from .import views
urlpatterns = [
path('admin/', admin.site.urls),
path('articles/', include('articles.urls')),
path('about/', views.about),
re_path('^.*$', views.homepage)
]
from django.http import HttpResponse
from django.shortcuts import render
#Views
def homepage(request):
# return HttpResponse('homepage')
return render(request, "homepage.html")
def about(request):
# return HttpResponse('about')
return render(request, "about.html")
Im getting no errors or such.
So, my question is - does anybody have a clue why /articles generate 404 error?
Thank you in advance.
Firstly, don't use ^$ with path(). You only use regular expressions with re_path.
path('', views.article_list),
Usually, /articles will be redirected to /articles/ with a trailing slash.
However, in your case, you have a catch-all pattern:
re_path('^.*$', views.homepage)
This matches /articles, so you see the home page. Note it's not redirected as you say in your answer, the browser bar will still show /articles.
Unless you have a really good reason to have the catch all, I suggest you remove it and change it to
re_path('^$', views.homepage),
or
path('', views.homepage),
That way, you'll see the homepage for localhost:8000, localhost:8000/articles will be redirected to localhost:8000/articles/, and you'll get a 404 for pages that don't exist, e.g. localhost:8000/art/
Just using a empty string '' instead of '^$:
urlpatterns = [
path('', views.article_list),
]
Take a look at the last example here: https://docs.djangoproject.com/en/3.1/topics/http/urls/#url-namespaces-and-included-urlconfs
*I don't know what django version are you using, but for regular expressions paths you should use re_path() https://docs.djangoproject.com/en/3.1/ref/urls/#django.urls.re_path
I'm learning how to do web programming with Django framework and I got this error message when I try to return a template. When I try to load https://www..../index2/ everything is ok.
This is my urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^index2/$', views.index2, name='index2'),
]
This is my views.py:
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'main/index.html',)
def index2(request):
return HttpResponse("Hello, world.")
Make sure you have index.html saved under app/templates/main/index.html
if you have debug mode enabled. Exception page will show you the different paths from where django is trying to load index.html.
Thanks.
I added in init.py of my project:
import django
django.setup()
Everything is working correctly.
However I am facing problems whit module urls when I try to import "reverse" from "django.urls". I get the error "No module named urls". I can't understand why I have this error (for the moment I am using "django.core.urlresolvers" to impor "reverse", but I'd like to understand the mistake)
I am using Django 1.11.16 and python 2.7.
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.
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()),
)