How to pass a views variable to a template using Django - python

After checking several similar threads I still fail to get it work. I want to pass a simple variable from my views.py to my index.html template. But the template displays the variable 'liga1' as it is in the frontend and the variable's value isn't passed.
These are my files:
views.py
import requests
from django.shortcuts import render
import json
# Render different pages
def render_landing_page(request, template="index.html"):
liga = ['1. Bundesliga', 'Premier League', 'La liga']
return render(request, template, {'liga': liga})
index.html (only a snippet):
<!-- Sidebar -->
<div id="sidebar">
<header>
Dasocc
</header>
<ul class="nav">
<li class="countries"><img src="{% static "images/germany.png" %}" alt="germany">{{ liga }}
urls.py // project dir
from dasocc_app import views
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^$', views.render_landing_page, name='landing_page'),
url(r'^$', views.liga, name='liga'),
url(r'^dasocc-app/', include('dasocc_app.urls')),
url(r'admin/', admin.site.urls),
]
urls.py // app dir
from django.conf.urls import url
from dasocc_app import views
urlpatterns = [
#Where home is some random view from your dassocc-app
url(r'^$', views.liga, name='liga')
]
No html output at the frontend for {{ liga }} variable in index.html template:
Related project structure:

For some reason you have added your templates to your urls.py. Even though you haven't told us what URL you are going to, it is clear from the output that you are visiting the template address directly and not going to the URL that is served by the liga view.
Remove the templates from your URLs and add a URL which points to liga.

Related

Django not serving text content (Second attempt)

Summary:
I’m writing a Django web app whose purpose is to showcase a writing sample (a ‘post mortem’) which is basically like a blog post for all intents and purposes. Django is not serving the content and I am not sure why. The problem I figure is with either my views.py or template (copied below). I don’t think the issue is with my models or urls.py but I included them anyways.
Details:
This is my second attempt at getting my Django project to serve this template properly. In my prior first attempt, I encountered a similar issue:
Django not serving text content (First attempt)
There in that question, another SO member answered by identifying three mistakes I was making. The problem there was that I was missing a for loop inside my template, I was missing an all() class method inside my views.py and the context dictionary key value pair in views.py was not pluralized.
Those issues have been resolved however my new issue involves Django serving a blank template when I am expecting the Lorem Ipsum content to show.
Django should be pulling all the class objects from my models.py and then be sending them to the alls/landings.html. I am expecting the title, publication date, image and body content to render on my landing page. But instead, my ‘mortems’ app content (a blog post) isn’t showing on the landing page. The only thing that shows is the heading. To illustrate so you can see what I see, here is what my landing page looks like now:
Based on what you people see below, who can tell me what is wrong with my views / landings.html template?
The full source code can be found on my GitHub page. Here is a snapshot of the state of my project (tagged as v0.6.0).
What follows are the code samples where I suspect my issue exists.
Here is my latest views.py:
from django.shortcuts import redirect, render, get_object_or_404
from mortems.models import Mortem
def mortems(request):
mortems = Mortem.objects.all().order_by('-pub_date')
context = {'mortems':mortems}
return render(request, 'alls/landings.html', context)
Here is my templates/alls/landings.html:
{% load static %}
<html>
<head>
<title> BLOG </title>
<style> </style>
<!-- <link rel="stylesheet" href="{% static 'redactors/style.css' %}"> -->
</head>
<body>
{% block content %}
<h1> BLOG POST:</h1>
{% for mortem in mortems %}
<h1>{{ mortem.title }}</h1>
<h4>Date: {{ mortem.pub_date_preference }}</h4>
<br />
Image: <img src="{{ mortem.image.url }}" class="img-responsive center-block" style="max-height:300px;" />
<br />
<!-- Body text should go here : -->
Body Text:
<p>{{ mortem.body|safe }}</p>
<br />
<br />
{% endfor %}
{% endblock %}
</body>
</html>
Here my project’s main urls.py:
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('admin/', admin.site.urls),
path('', include('redactors.urls')),
path('', include('counters.urls')),
path('', include('mortems.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is my app’s (mortems) urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.mortems, name='mortems'),
]
Here is my app’s models.py:
from django.db import models
import datetime
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
# Create your models here.
class Mortem(models.Model):
title = models.CharField(max_length=161)
pub_date = models.DateTimeField()
image = models.ImageField(upload_to='media/')
body = models.TextField()
now = datetime.datetime.now()
def __str__(self):
return self.title
def pub_date_preference(self):
# a = self.pub_date.timezone.now("US")
b = self.pub_date.strftime("%A %d %B %Y # %-I:%M:%S %p")
# c = pytz.timezone("US")
return (b)
def summary(self):
return self.body[:1024]
You are using the same path for views.home in redactors.urls and views.mortems in mortems.urls i.e '/'
CC_Redact_Iter3/urls.py you configured in this order
urlpatterns = [
#Django serves urls in the order you gave
path('admin/', admin.site.urls), #1st
path('', include('redactors.urls')), #2nd
path('', include('counters.urls')), #3rd
path('', include('mortems.urls')), #4th
]
redactors/urls.py
urlpatterns = [
path('', views.home, name='home'), #here you have to change the home path
path('alls/results', views.results, name='results'),
]
mortems/urls.py
urlpatterns = [
path('', views.mortems, name='mortems'), #As you can see views.home is also having same path so change the path for home
]
In your case
def home(request):
if 'ccEntry' in request.GET:
number = request.GET['ccEntry']
redacted_num = 'xxxx xxxx xxxx {}'.format(number[-4:])
return render(request, 'alls/results.html', {'number':number, 'redacted_num':redacted_num})
else:
return render(request, 'alls/landings.html') #this is being rendered instead mortem
Change your CC_Redact_Iter3/urls.py and redactors/urls.py as shown below
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mortems.urls')),
path('', include('redactors.urls')),
path('', include('counters.urls')),
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns = [
path('home/', views.home, name='home'), #here you have to change the home path
path('alls/results', views.results, name='results'),
]
And the date format in you mortems/models.py is Invalid (%-I)
def pub_date_preference(self):
# a = self.pub_date.timezone.now("US")
b= self.pub_date.strftime("%A %d %B %Y # %I:%M:%S %p") #try something like this
# c = pytz.timezone("US")
return (b)
Courtesy of #MeL in the comments, the solution is to include ‘mortems’ as the first argument inside my path() function inside the mortems app’s urls.py. This file looks like this now:
urlpatterns = [
path('mortems', views.mortems, name='mortems'),
]
Now when I navigate to http://127.0.0.1:8000/mortems, the landings.html template renders exactly as intended, with all the content present. To see, here is my mortems page now:
So that is the solution I guess. But I remain flummoxed and curious: why? With the path parameter empty ’’, I’d expect Django to serve the landings.html template on the home page / landing page at this location: http://127.0.0.1:8000/. Django serves the template but all the content is missing. Only after adding a string as an argument the content shows. Why is that?
If someone could kindly answer why, I’d be happy to update this answer here with more information.

Django shows page not found

I'm learning Chapter 18 18.4.2 in Python Crash Course,when i open http://localhost:8000/topics ,I'm using Django 3.0 and python 3.8
shows
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/topics
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
The current path, topics, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
and this is my code
learning_log\urls.py
from django.contrib import admin
from django.urls import path
from learning_logs import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index,name = 'index')
]
learning_logs\urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index,name = 'index'),
url(r'^topics/$',views.topics,name='topics')
]
views.py
from django.shortcuts import render
from .models import Topic
# Create your views here.
def index(request):
return render(request,'learning_logs/index.html')
def topics(request):
topics = Topic.objects.order_by('date_added')
context = {'topics':topics}
return render(request,'learning_logs/topics.html',context)
base.html
<p>
Learning Log-
Topics
</p>
{% block content %}{% endblock content %}
topics.html
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>{{ topic }}</li>
{% empty %}
<li>No topics have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}
and runserver shows:
Not Found: /topics
[06/Jan/2020 17:53:15] "GET /topics HTTP/1.1" 404 2077
enter image description here
First of all, good question. Love the detail.
The error is the following
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order
This means that the url /topics cannot be found. You need to import that url from the app specific urls.py into the main urls.py. This is usually done by something along the lines of
# in main urls.py
from learning_logs.urls import urlpatterns as ll_urlpatterns
# other patterns ...
urlpatterns += ll_urlpatterns
Use below code replace 'app' with your appname.
from django.contrib import admin
from django.urls import path
from learning_logs import views
from django.conf.urls import url, include
urlpatterns = [
path('admin/', admin.site.urls),
url(r'', include(('app.urls', 'app'), namespace='app')),
]

Unable to render form in Django

I'm trying to import a simple single-field form in Django, and I have gone through plenty of Tutorial Videos on YouTube describing the same. Yet, I'm unable to render the simple form on my web-app. I'm pretty sure I'm doing something really stupid that is still oblivious to me.
I'll also post in the folder structure so you can suggest if I'm defining the class/function in the wrong views.py file.
The appropriate source codes are as follows:
earthquake/views.py File
from django.shortcuts import render
from earthquake.forms import HomeForm
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = 'earthquake/home.html'
def get(self, request, *args, **kwargs):
form1 = HomeForm()
argf = {
'myform': form1
}
return render(request, self.template_name, argf)
forms.py
from django import forms
class HomeForm(forms.Form):
post = forms.CharField()
home.html (snippet)
<div class="container">
<div class="jumbotron">
<h1>Query Form</h1>
<p>Please Enter the parameters you want to query against the USGS Earthquake DB</p>
<div class="container">
<form class="" method="post" action="">
{% csrf_token %}
{{ myform }}
<button type="submit" class="btn btn-success">Search</button>
</form>
</div>
</div>
</div>
Django Project urls (interview.py/urls.py)
from django.contrib import admin
from django.urls import path, include
from interview.views import login_redirect
from interview import views
from django.contrib.auth.views import LoginView
from django.contrib.auth.views import LogoutView
urlpatterns = [
path('', login_redirect, name='login_redirect'),
path('admin/', admin.site.urls),
path('home/', include('earthquake.urls')),
path('login/', LoginView.as_view(template_name='earthquake/login.html'), name="login"),
path('logout/', LogoutView.as_view(template_name='earthquake/logout.html'), name="logout"),
path('register/', views.register, name='register'),
]
App URLS (interview/earthquake/urls.py)
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Folder Structure
https://i.stack.imgur.com/zoehT.jpg
(In case you're unable to see the last entry in the image, it's the main views.py present in the project folder).
The following is the snapshot of the render I currently get:
https://i.stack.imgur.com/kXR7W.jpg
I see that in your home views file your class based view is called
HomeView(TemplateView)
Yet in your app urls you are including the view as view.home when it should be
view.HomeView
to add to that, this is a classed based view so your urls page for that should look like:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home.as_view(), name='home'),
]
Since this is a class based view.

Media Files not Displaying in Django

I am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for gallery images with a filefield), the image is stored in /media/images correctly. I have my media settings set in settings.py as follows:
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
import gallery.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('gallery.urls')),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Gallery urls.py:
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^', views.homepage, name = 'home'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Gallery views.py:
def homepage(request):
texts = Sitetext.objects.all()
gal = Galleryimg.objects.all()
gal.order_by('position')
return render(request,'index.html', {"text1":texts[0].text,"text2":texts[1].text,"text3":texts[2].text,"text4":texts[3].text,"title1":texts[0].title,"title2":texts[1].title,"title3":texts[2].title,"title4":texts[3].title,"gallery":gal})
And then this is the part of the template code that accesses the image:
{% for g in gallery %}
<div class="col-md-3 col-sm-4 col-xs-6">
<img class="img-responsive" src="g.imgfile.url" />
</div>
{% endfor %}
When I create a gallery image, a broken image pops up, but the image is not accessed correctly.
I do this and I am able to serve media files from the Django development server:
urlpatterns += [
url(r'^media/(?P<path>.*)$', django.views.static.serve, {
'document_root': settings.MEDIA_ROOT}),]
It should be enough to include that just in the project urls.py.
The issue with yours could be that your media URL entry in urls.py is not correct. You seem to be not matching the actual URL of the media file, which is probably something like /media/something.png. You seem to be just qualifying on /media/. I also think your regex should be ^media/, not /media/.
Remove the static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) part, from your gallery.urls file.
Replace src="g.imgfile.url" with src="{{ g.imgfile.url }}".
Aside question: Why do you pass this big dictionary ({"text1":texts[0].text,...) to your template? It is error prone and bad practice. You should just pass 'texts': texts and inside your template iterate over them with a {% for text in texts %} forloop. So, the render method should be something like render(request, 'index.html', {'texts': texts, 'gallery': gal}).

how to send a parameter from html to django view.py

I am a beginner and did a lot of search but every time I got only "django to html" as search result every time. I am following this tutorial:
http://www.djangobook.com/en/2.0/chapter07.html
but on the way I am not able to pass paramter from html to view.py.
Here is my directory:
directory: mysite:
directory: books
directory: templates
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
views.py
from django.shortcuts import render
from django.http import HttpResponse
def search_form(request):
return render(request, 'books/search_form.html')
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
urls.py for books
from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^$',views.search_form,name='search_form'),
url(r'^$', views.search,name='search'),
]
and urls.py in mysite directory
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import url, include
3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/', include('books.urls')),
]
Now the problem is when I type: http://127.0.0.1:8000/books/
it successfully shows the form's textbox and submit button but when I press submit it shows me this:
Firstly, you need two different regexes for the search_form and search results. For example:
url(r'^$',views.search_form,name='search_form'),
url(r'^search/$', views.search,name='search'),
Next, you need to update the form's action to point to the search view. Since you have included your books/urls.py with the /books/ prefix, you need:
<form action="/books/search/" method="get">
It is better to use the url tag instead of hardcoding your urls. In this case, you would do:
<form action="{% url 'search' %}" method="get">
In addition to the answer of Alasdair I would use "books:search" for clear namespace:
<form action="{% url 'books:search' %}" method="get">
The url /search/ doesn't exist, you didnt define that it should exist.
It would be /books/ judging from that URLs file you showed. Also on a side note, don't use http://www.djangobook.com/en/2.0/index.html
They have a warning on the main page that it is no longer up to date.
Use masteringdjango.com and other up to date resources.

Categories

Resources