Django can't find HTML file - django

I have a html file ('search.html') with a form on it. I have saved it to ~/Django/Templates just for the sake of argument. The Django book said it doesn't matter where I save it, because the framework will find it. Anyway, I have set up a function in the views.py file to render this file. Here it is:
from django.http import HttpResponse
from django.shortcuts import render_to_response
def search(request):
return render_to_response('search.html')
I have this function called in the urls.py file as well:
urlpatterns = patterns('',
(r'^$', index),
(r'^search/$', search),
However, whenever I go to visit the page with the ~/search in the URL, I get the following:
TemplateDoesNotExist at /search/
What's the problem?

In your settings.py file there is a line...
TEMPLATE_DIRS = (...)
You want to make sure the directory containing the template is in that tuple.

Related

Page not found for the template returned by TemplateResponse in Django

I have an app which is called sitepages which have three models I wanna pass their objects to a html page called listing.html which is inside templates/sitepages
the sitepages urls.py contains:
from django.views.generic import TemplateView
from django.urls import include
from django.urls import path
from sitepages import views
app_name = "sitepages"
urlpatterns = [
path("news-events-listing/", views.view, name='listing'),
]
the sitepages/views.py:
from .models import Listing, Details1, Details2
from django.template.response import TemplateResponse
def view(request):
return TemplateResponse(request, 'sitepages/listing.html', {
'first_pages': Details1.objects.all(),
'seconde_pages': Details1.objects.all(),
'listing_page': Listing.objects.first(),
})
in the root urls.py I added:
path("", include("sitepages.urls", namespace='sitepages'))
when I put in any template the following:
Listing
it redirects me to the url /news-events-listing but no page is found and it gives me 404 error...what am I doing wrong? why the template is not returned? I should mention that I'm using wagtail for the whole site (I don't know if it's related)
In your root urls.py, make sure your new line
path("", include("sitepages.urls", namespace='sitepages'))
appears before the path("", include(wagtail_urls)) line. The wagtail_urls pattern matches any URL path and passes it to Wagtail to be handled as a Wagtail page, so any patterns after it will never be reached.

Python - Django add multiple urlpatterns for multiple views of template

I'm very very new to Python 3 and Django and I get to the following problem: I use a standard Template and now how to set it up when there is 1 view. But I don't get the code right for multiple views. I currently run the page locally
At the moment I have tried to change different orders within urlpatterns, and they do work when only 1 url in in there, but I can't get the second one in
views.py
from django.shortcuts import render, render_to_response
# Create your views here.
def index(request):
return render_to_response('index.html')
def store(request):
return render_to_response('store.html')
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from myapp import views as views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^store/$', views.store, name='store'),
url(r'^admin/', admin.site.urls)
]
urlpatterns += staticfiles_urlpatterns()
I would like the url pattern that lets me go to the index view and the store view
EDIT:
Full code is shared via: https://github.com/lotwij/DjangoTemplate
The error in the comments shows you are going to http:/127.0.0.1:8000/store.html, but your URL pattern url(r'^store/$', ...) does not include the .html, so you should go to http:/127.0.0.1:8000/store/.
The Django URL system uncouples the URL from the name of the template (sometimes the view doesn't even render a template!). You could change the regex to r'^store.html$ if you really want .html in the URL, but I find the URL without the extension is cleaner.

Django: cannot import name 'url_patterns'

I have a weird edge-case where I need to use the data stored in urls.py within a view, but since the urls.py file imports the view, I am getting a circular import error when I try to import the url data into the view.
cannot import name 'url_patterns'
Does Django have any way of grabbing all the url patterns within a view that could circumvent this error? The fact that the reverse() function exists indicates that it might.
You can solve this typically (well it depends a bit), by importing the urls in your view(s) locally. Like:
# urls.py
import someapp.views
url_patterns = [
url('some_url/', someapp.views.some_view),
]
and then import the urls in the views like:
# views.py
def some_view(request):
from someapp.urls import url_patterns
# ...
# do something with urlpatterns
# return response
pass
We here thus postpone the importing of the urls.py in the views, until the view function is actually called. By that time both the views.py and urls.py are (usually) already loaded. You can however not call the view in the views.py directly, since then the import is done before the urls.py is loaded.
Note that usually you do not have to import url_patterns, and you can use reverse(..) etc. to obtain a URL that corresponds to a view function (even passing parameters into a dictionary, etc.). So I really advice to look for Django tooling to handle URLs.
Found an answer:
from django.urls import get_resolver
url_patterns = set(v[1] for k,v in get_resolver(None).reverse_dict.items())

django urls: "Django tried these URL patterns"

I am trying a tutorial on Django called blog. I have the following structure:
FirstBlog|FirstBlog
settings
urls
__init__
etc
blog
templates | index.html
migrations
views.py
manage.py
The view.py has
from django.shortcuts import render
from django.shortcuts import render_to_response
from blog.models import posts
def home(request):
return render('index.html')
The urls.py has
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
urlpatterns = [
url(r'^blog', 'FirstBlog.blog.views.home',name='home'),
]
and I get this error:
Using the URLconf defined in FirstBlog.urls, Django tried these URL patterns, in this order: ^blog [name='home']
The current URL, , didn't match any of these.
I can't seem to get it right..
Any help would be appreciated.
Thank you,
You are requesting for / url and you have not saved any such mapping. Current mapping is for /blog . So it will work for the same url.
i.e goto the browser and request /blog
If you need it to work for / then change the urls appropriately.
within your blog app, create a urls.py file and add the following code which calls the home view.
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^',views.home, name='home'),
]
then in your root urls file which can be found at FirstBlog/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^blog/',include('blog.urls')), #when you visit this url, it will go into the blog application and visit the internal urls in the app
]
PS:
your templates should be in blog/templates/blog/index.html
Read this docs on templates to understand how django locates templates.
This one is to understand how urls work Urls dispatcher
You are doing this in the wrong way! Try doing that using TemplateView from class-based views, which are the current standard from django views.
Check the django documentation: https://docs.djangoproject.com/en/1.9/topics/class-based-views/
Use this at the urls.py:
from django.conf.urls import url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^blog/', TemplateView.as_view(template_name="index.html")),
]
And then, create a folder called templates in the project root ( like this: https://docs.djangoproject.com/en/1.9/intro/tutorial03/#write-views-that-actually-do-something ) named index.html
Simply go to file then select Save all your project instead of save. Or use shortcut Ctrl +k s on windows. Project should be able to sync and display the code on Django interface

Django RequestContext and media doesnt work

I'm beginner, but I've been looking everywhere for solution. I can't see uploaded images (404).
Error from image link (for example:http://192.168.1.1:8000/media/portfolio/icon.png/ -> by the way, this proper url ) :
No SuperPages matches the given query.
SuperPages is my model which contains url object.
I configured everything for media files like here: http://www.muhuk.com/2009/05/serving-static-media-in-django-development-server/. And to be clear, when I'm using generic views only, it works great. But with views, I can't see images (links to images are fine). Static files works great. So this is my code:
urls.py
from mysite.cms.views import superpages
urlpatterns = patterns('',
(r'^(?P<url>.*)$', superpages),)
views.py
from django.template import loader, RequestContext
from mysite.cms.models import SuperPages
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
DEFAULT_TEMPLATE = 'default.html'
def superpages(request, url):
if not url.endswith('/') and settings.APPEND_SLASH:
return HttpResponseRedirect("%s/" % request.path)
if not url.startswith('/'):
url = "/" + url
f = get_object_or_404(SuperPages, url__exact = url)
t = loader.get_template(DEFAULT_TEMPLATE)
c = RequestContext(request, {
'superpages': f,
})
return HttpResponse(t.render(c))
There's something wrong with your urls.py. I suppose you have defined your patterns like this:
urlpatterns = patterns('',
(r'^(?P<url>.*)$', superpages),
(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
A URL such as http://192.168.1.1:8000/media/portfolio/icon.png/ matches the first pattern so your superpages view is called and raises a 404. What you need to do is put your catch-all superpages pattern at the very end of your urlpatterns. Or you can choose a different approach with a middleware, see what django.contrib.flatpage does for an example.