Why is the Django template file not updating value from the context? - python

(I am a beginner in Django)
I am following along a tutorial in Django where we can dynamically pass some variable to a template file from associated function in views.py
When I am running the code for the first time, it works fine, but when I change the values within the context, the template does not update with the new values even when I refresh it
Here is my views.py code -
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
# return HttpResponse('<h1>Hey, welcome</h1>')
# we can dynamically send data to our index.html file as follows -
context={
'u_name': 'Ankit',
'u_age': 25,
'u_nationality': 'Indian',
}
return render(request,'index.html',context)
Here is my template index.html -
<h1>
How are you doing today {{u_name}} <br>You are {{u_age}} years old<br>Your nationality is {{u_nationality}}
</h1>
settings.py has been correctly set as well -
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR,'templates'],
Editing post to add urls.py as well (this is within the app)
from . import views
from django.urls import include,path
urlpatterns = [
path('',views.index,name='index')
]
And the urls.py in the main project -
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MyApp.urls'))
]
Here is my output -
does not take the values from the context
Would be glad if someone could point out what error I am making. Thanks in advance

Related

django.core.exceptions.ImproperlyConfigured: error is coming

I am new to Django and hence don't have much idea about it. I am trying to create an app having the following contents in my view.py file:
from django.shortcuts import render
from fusioncharts.models import City
def pie_chart(request):
labels = []
data = []
queryset = City.objects.order_by('-population')[:3]
for city in queryset:
labels.append(city.name)
data.append(city.population)
return render(request, 'pie_chart.html', {
'labels': labels,
'data': data,
})
The content of my urls.py file inside the app is as follows:
from django.urls import path
from fusioncharts import views
urlpatterns = [
path('pie-chart/', views.pie_chart, name='pie-chart'),
]
and the content of my urls.py file inside the main project folder is as follows:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('fusioncharts.urls'))
]
In the settings.py file, I have added the following:
ROOT_URLCONF = 'Piechart.urls'
and under the TEMPLATES, added the following:
'DIRS': ['Piechart/fusioncharts/templates'],
Now while running my app, I am getting the following error:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'Piechart.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
Can anyone please say what's going wrong?
you forgot to import include in the project urls.py, i was about to comment this but can't in my current reputation level.
from django.urls import path,include

I'm getting 404 error on every page in django

I'm developing my first app in Django and facing some issues. The server runs smoothly and I can operate the admin panel without any issues.
However, all of the app pages including the default homepage show a "404 not found" error.
I have created a templates directory in project root
updated this line in settings.py for templates,
'DIRS': [os.path.join(BASE_DIR,'templates')],
View for the app
from django.shortcuts import render
from .models import *
# Create your views here.
def customers(request):
customers = Customer.objects.all()
return render(request, "customers.html", {'customers': customers})
urls for the app
from django.urls import path from . import views
urlpatterns = [path('customers',views.customers, name='customers')]
urls for the project
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static
urlpatterns = [
path('trips/',include('trips.urls')),
path('customers/',include('customers.urls')),
path('drivers/',include('drivers.urls')),
path('vehicles/',include('vehicles.urls')),
path('admin/', admin.site.urls), ]
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Help is appreciated
I can't see any problem with your case, you should be able to load http://localhost:8000/customers/customers. Maybe double customers was not you intention, then remove one of them (one in main urls.py one in app's).
Also when Django debug mode is active and you get a 404 because of URL mismatch, it shows you a list of URLs you have. To see it navigate to a non existing URL like http://localhost:8000/aaa. Then if you see customers/ there try http://localhost:8000/customers/. Go step by step to find the problem.

django 404 not found page

I am trying to show a blogpost on the site.
Below is details of urls and view file details but still it showing a 404 not found page
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="ShopHome"),
path("blogpost/", views.blogpost, name="blogpost")
]
views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return render(request, 'blog/index.html')
def blogpost(request):
return render(request, 'blog/blogpost.html')
Showing:
404 not found page
you should include urls.py of your application to project urls.py
actually if your project name is "mysite" and your application name is "blogspot", you should include mysite/blogspot/urls.py on this file mysite/mysite/urls.py like this:
from django.urls import path, include
urlpatterns = [
path('', include('blogspot.urls')),
]
Actually, i forget to add the slash at the time of registering the url of this app in urls

How to point django to put a template in the front page

I am trying to learn python in the django framework, I took a course, but it was based on an earlier version of django while I am using Django 2.1.3 and python 3.7.0, so I've got errors.My question is how can I point urls.py to take an html template and put it in the main page in this version of Django?
Thank you!!
You should point urls.py to views.py for your home page.
So your urlpatterns would look like, your main app:
urlpatterns = [
path(r'', include('page.urls'))
]
urls.py in page app:
urlpatterns = [
url('^$', views.page, name = 'index')]
And views.py like:
def page(request):
return render(request,"page.html")
There is tons of tutorials online. Have a look on Django documentation or YouTube . I also have blog with some info (I started learning recently too) https://adamw.eu
I assume Front page stands for Home page and that your site is called website. Then in urls.py of website/website (the directory that also contains the settings.py file), create a HomePage view
from django.views.generic import TemplateView
class HomePage(TemplateView):
template_name = 'index.html'
Then in urls.pyin the same folder, do something like:
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.HomePage.as_view(), name="home"),
]
You then need a templates folder at the root of your website, that is in website/templates and create website/templates/index.html which will be your homepage template.
In the website/website/settings.py file, make sure to set TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') and modify the TEMPLATES variable:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
... # rest of the code here
Reboot server, this should work fine.

How to return a static HTML file as a response in Django?

I have not figured out how I can present a website with pure HTML code and/or HTML + JavaScript + CSS.
I tried to load an HTML file that just says: Hello World.
I know I can do that with Django too, but later on, I want to display my website with CSS+JavaScript+HTML.
In the views file I run this code:
# Create your views here.
from django.http import HttpResponse
from django.template import Context, loader
def index(request):
template = loader.get_template("app/index.html")
return HttpResponse(template.render)
But the only thing the website displays is:
If your file isn't a django template but a plain html file, this is the easiest way:
from django.shortcuts import render_to_response
def index (request):
return render_to_response('app/index.html')
UPDATE 10/13/2020:
render_to_response was deprecated in Django 2.0 and removed in 3.0, so the current way of doing this is:
from django.shortcuts import render
def index (request):
return render(request, 'app/index.html')
You are not calling the render method there, are you?
Compare:
template.render
template.render()
If your CSS and JS files are static don't use Django to serve them, or serve them as static files
For your html you could do the same if it is just some fixed file that won't have any dynamic content. You could also use generic views with the TemplateView, just add a line like this to your urls.py:
url(r'^path/to/url', TemplateView.as_view(template_name='index.html')),
By using HttpResponse you can send data only, if you want to html file then you have to use render or render_to_response by following ways...
from django.shortcuts import render
def index(request):
return render(request, 'app/index.html')
or
from django.shortcuts import render_to_response
def index (request):
return render_to_response('app/index.html')
First, you need to do some settings for templating:
Create "templates" folder in the root directory, where manage.py is located after you created your project.
Then go to settings.py , in the TEMPLATES section enter the directory of templates folder. Hard coding is not recommended because if you send your project to your friend, your friend won't be able to run it. Should be like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,"templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Assuming that you have home.html and about.html have in templates folder:
urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('about/',views.aboutview),
path('',views.homeview),
]
views.py
from django.http import HttpResponse
from django.shortcuts import render
def aboutview(request):
return render(request,"home.html")
def homeview(request):
return render(request,"about.html")
from django.http import HttpResponse
from django.template import loader
def index(request):
template=loader.get_template('app/index.html')
return HttpResponse(template)

Categories

Resources