Django templates won't load but HttpResponse will - python

I recently began learning django and have been running into some trouble and I can't figure out why.
My problem is quite simple: whenever I try to run my homepage with a template, it throws up a 404 error.
My file hierarchy is as such:
crm
accounts
templates
accounts
dashboard.html
urls.py
views.py
crm
urls.py
In crm/urls, I have
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('accounts.urls'))
Then in accounts/urls, there is,
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
And in views, I have
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request, 'accounts/dashboard.html')
My dashboard.html is just a basic html file with a title and h1, that's it.
Also, whenever I change
return render(request, 'accounts/dashboard.html')
to
return HttpResponse('home')
in my home function, it decides to show.

Your dashboard.html is inside a folder, so it should be referenced like accounts/dashboard.html
Relevant docs: https://docs.djangoproject.com/en/3.0/intro/tutorial03/#a-shortcut-render
In their example, they are using polls/index.html (scroll a bit up from the linked position in the docs). It is analogous to your accounts/dashboard.html in placement (both are in a subfolder as they should be).
Django looks for templates across multiple apps in the same way it searches for static files. Except that you can "see" static files being copied over to a separate folder with manage.py collectstatic while templates get "discovered" in place and not copied anywhere. In facg, if you are running manage.py runserver then the static files are also discovered in place, so the logic is the same.
One difference is that template loading can be changed by using a different set of loaders (docs on template loaders, but by default (and for the majority of projects I guess) this similarity holds.

Related

Django load wrong template

I am new to Django. I am trying to configure an app called 'faq', and an index page to display the different "apps", including the previous one.
I was following the Learn Django site guide to decide what was best for the template structure.
So, I configured myproject/settings.py to let load the template from templates folder: 'DIRS': ['templates'],.
In the app folder myproject/apps/faq I have created a templates folder.
In the app views myproject/apps/faq/views.py I defined the views to load the data from database and send it back to the template:
from django.shortcuts import render
from .models import *
def faqs_view(request):
faqs = FrequentAskedQuestion.objects.all()
context = { 'faqs': faqs }
return render(request, 'index.html', context)
def faq_view(request, id):
faq = FrequentAskedQuestion.objects.get(id=id)
print(faq)
context = { 'faq': faq }
return render(request, 'detail.html', context)
In the app folder I have created a URLconf configuration in myproject/apps/faq/urls.py:
from django.urls import path
from .views import faqs_view, faq_view
urlpatterns = [
path('', faqs_view, name='faq-list'),
path('<int:id>', faq_view, name='faq-detail'),
]
A parenthesis here, since the first attempt I have tried to create a project templates folder and use the project views.py and urls.pyand it didn't work I decided to create another app called main.
In the app folder myproject/apps/main I have created a templates folder.
In the app views myproject/apps/main/views.py I defined just a simple view to render the app list:
from django.shortcuts import render
def index_view(request):
return render(request, 'index.html')
In the app folder I have created also a urls.py and added the previous view:
from django.urls import path
from .views import index_view
urlpatterns = [
path('', index_view, name='site-index'),
]
In the project URLconf file I have added both apps:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('myproject.apps.main.urls'), name='site-index'),
path('admin/', admin.site.urls, name='admin-index'),
path('faq/', include('myproject.apps.faq.urls'), name='faq-index'),
]
After the previous setup I got working 'faq' app and it works great. But, whenever I go to http://localhost:8000/ it display the title from myproject/apps/faq/templates/index when it should display myproject/apps/main/templates/index.
Maybe it is worth to mention that both templates (main/templates/index and faq/templates/index) inherit from a base template that is created in each app template folder.
The file tree:
myproject
apps
faq
templates
base.html
index.html
urls.py
views.py
main
templates
base.html
index.html
urls.py
views.py
settings.py
urls.py
I am doing something wrong. So, any clues?
Typically you write the name of the app under the templates directory, so:
faq/
templates/
faq/
index.html
This creates a sort of "namespace", such that you can reference to the correct file with:
from django.shortcuts import render
def index_view(request):
return render(request, 'faq/index.html')
If you do not construct such directory, then Djangno will simply search for a file named index.html in all the template directories. So if there are multiple, it depends on the order in which the template directories are searched.

Refer to my (reusable) app's url namespace in Django

I want to write a reusable Django application.
I tell my users to add the following to their urls.py
path('slack/', include(('slack_integration.urls', 'slack_integration'), namespace='slack_integration'),
And in my urls.py I want to have a view login_callback.
Now in my view, I need to get a value of slack_integration:login_callback.
I can trust the user that he/she will integrate it with slack_integration prefix and use it. But is this the best practise? Can I somehow get the name of the namespace for the app if user chooses a different name for it?
Thanks a lot!
Using namespace= within urls.py files is no longer supported, as it moves something specific to the Django app outside of the Python package that is the Django app.
The best practice now is to define the app_name within the urls.py file inside the Django app.
The old way: DON'T DO THIS (pre-Django 2.0)
the root urls.py
path('slack/', include(('slack_integration.urls', 'slack_integration'), namespace='slack_integration'),
The new way: DO THIS! (Django 2.0+)
the root urls.py
from django.urls import path, include
urlpatterns = [
path('slack/', include(('slack_integration.urls', 'slack_integration')),
]
slack_integration/urls.py
from django.urls import path
app_name = "slack_integrations"
urlpatterns = [
path('', HomeView.as_view(), name='home'),
]
As you can see, this keeps the namespace for the patterns within the app itself, along with the templates most likely to use it. The days of extra instructions on how to include an app are over! Good luck.

Django cant be reached via parameterized url

Hello StackOverflow community,
I'm currently learning how to use the library Django combined with Python. However, I've ran into some issues which are somehow strange. My situation is the following. I have a project called "animals" which is the base of the Django application. My app is called "polls". Then I've defined the following views.
polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
def animals(request, animal_id):
return HttpResponse("%s" % animal_id)
def index(request):
return HttpResponse('Hello world')
So far, so good. Unfortunatly I can't say the same about the urlpatterns.
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
# Redirects to localhost:8000/polls/<animal_id>
path('<int:animal_id>/',views.animals,name='animals')
]
Whenever I want to navigate to the url "localhost:8000/polls/10/" Django reminds me of the fact, that the url is not accepted by the application and a 404 Error is thrown inside my browser. Am I missing something here?
UPDATE
I've managed to resolve the problem by fixing a rather trivial error. While the polls/urls.py was alright, the problem lay inside the animals/urls.py file. This file looked like this:
animals/urls.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
url(r'^admin/', admin.site.urls),
path('polls',include('polls.urls')),
]
As one can see, the "polls" path is not finished with a "/" sign. This indicates to Django that my desired route would be localhost:8000/polls where is any integer I add to the url. However, you have to add the slash at the end. Otherwise Django won't work as expected.

When I try to write something in Django urls.py file, it doesn't show this in the browser

#code in urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name= 'index'),
path('about/', views.about, name ='about'),
]
#code in views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello")
def about(request):
return HttpResponse("about harry")
Body
I am doing this while watching a tutorial, and the same thing is working for him. Moreover, if mistakenly I write the wrong code and run, cmd shows the errors and on reloading the browser the server doesn't work more. Then I need to restart CMD and again run manage.py. Please tell me the reason and also the solution, Thanks.
What errors do you get?
Besides there're 2 urls' files: url routes for pages are inside urls.py in the same folder where views.py are. In another urls.py (the one which is in the same folder with manage.py) you may need to write following, assuming that 'polls' is the name of you application:
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
]
According to Django docs: include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.
If you still get the error: check that you’re going to http://localhost:8000/polls/ and not http://localhost:8000/

django redirect inside of urls.py

I plan on having several different apps inside my django project, each for a new technology I want to play around with. As I work on each on, I want to have the root URL path redirect to the project I'm working on.
Directory Structure:
backyard/
my_project/
views.py
backyard/
urls.py
backyard/backyard/urls.py:
from django.conf.urls import patterns, include, url
from django.shortcuts import redirect
urlpatterns = patterns('',
url(r'^$', redirect('my_app/')),
url(r'^my_project/$', 'my_project.views.homepage'),
)
backyard/my_project/views.py
def homepage(request):
return render_to_response('my_project/index.html', {'data':data})
When I access the page at http:machine-name:8000/ I get an error saying The included urlconf backyard.urls doesn't have any patterns in it I most definitely have URLs in my urls.py, what is the issue?
A URLconf needs to map regexes to views -- the redirect function doesn't return a view; rather, it returns an HttpResponse. You can look at this question for an example of how to define a redirect directly in the URLconf.

Categories