Hi I'm trying to build a simple django app but I can't get index.html file to recognise the variables created in views.py. Nothing I do seems to work. Does it have to be configured somehow in settings.py perhaps?
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>Hello world {{ name }}</p>
</body>
</html>
views.py:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
context = {'name' : 'Peter'}
return render(request, 'index.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index')
]
Whatever I try, the browser just doesn't recognise anything in the {{}}. It just leaves it blank. I seem to have tried everything. Please help, I'm tearing my hair out.
Here's the github repo if anyone cares to look at it:
https://github.com/Peterhague/stacqato2
Thanks
CodePudding user response:
In your 'stacqato/settings.py' file I see that you have not added your app to the list of installed apps. You should add 'stack.apps.StackConfig' to INSTALLED_APPS in 'stacqato/settings.py'
In your settings.py file, in the TEMPLATES-section, APP_DIRS is true, so you should create a directory 'stack' under your 'templates' directory and move the 'index.html' file to the 'templates/stack' directory.
I mostly use class based views, so in your views.py that would become something like:
class IndexView(generic.View):
template_name = 'stack/index.html'
context = {'name': 'Peter'}
def get(self, request, *args, **kwargs):
return render(request, self.template_name, context)
In your urls.py that translates to:
path('', views.IndexView.as_view(), name='index'),
CodePudding user response:
I took a look at your Github repo. You didn't mention stack app in installed apps
CodePudding user response:
I think you're missing a slash before index.html in your render statement. Try this:
return render(request, '/index.html', context)