Global variable doesn't work inside django views - python

I wanted to use some dummy data in my Django views to work with templates. When the posts variable is outside the home function all I'm getting is an empty body. Although when I move it inside everything displays as it should.
from django.shortcuts import render
posts = [
{
'author': 'Kamil',
'title' : 'Post 1',
},
{
'author': 'Tomek',
'title' : 'Post 2',
},
]
def home(request):
context = {
'posts' : posts
}
return render(request, 'blog_app/home.html', context)
Here is also my html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% for post in posts %}
<h1>{{ post.title }}</h1>
<p>By {{ post.author }}</p>
{% endfor %}
</body>
</html>

Make posts a global variable
global posts
posts = [
{
'author': 'Kamil',
'title' : 'Post 1',
},
{
'author': 'Tomek',
'title' : 'Post 2',
},
]

Related

Multiple images are showing in django image grid

I am somewhat new to Django. I am making an image grid (html). But the images are shown multiple times in that grid. This is what I mean;
Here are my files;
Views.py
from django.shortcuts import render
photos = [
{
'user_im': 'https://thumbor.forbes.com/thumbor/fit-in/416x416/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5f47d4de7637290765bce495%2F0x0.jpg%3Fbackground%3D000000%26cropX1%3D1398%26cropX2%3D3908%26cropY1%3D594%26cropY2%3D3102',
'photo': 'https://images.unsplash.com/photo-1515199967007-46e047fffd71?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=975&q=80',
'date_shared': '4th January, 2020',
'caption': 'A wonderful pic',
},
{
'user_im': 'https://cdn.britannica.com/67/19367-050-885866B4/Valley-Taurus-Mountains-Turkey.jpg',
'photo': 'https://images.unsplash.com/photo-1547500135-9f6e5a9a6aff?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1050&q=80',
'date_shared': '4th January, 2020',
'caption': 'A nice picture',
},
{
'user_im': 'https://cdn.britannica.com/67/19367-050-885866B4/Valley-Taurus-Mountains-Turkey.jpg',
'photo': 'https://i.guim.co.uk/img/media/6088d89032f8673c3473567a91157080840a7bb8/413_955_2808_1685/master/2808.jpg?width=1200&height=1200&quality=85&auto=format&fit=crop&s=412cc526a799b2d3fff991129cb8f030',
'date_shared': '4th January, 2020',
'caption': 'A nice picture',
}
]
def home(request):
context = {
'photos': photos,
}
return render(request, 'photos/home.html', context)
def explore(request):
context = {
'photos': photos,
}
return render(request, 'photos/explore.html', context)
grid.py
{% extends 'photos/base.html' %}
{% block content %}
<h1><strong>These are some of the best</strong></h1>
<h5 class="text-muted">Just for you...</h5>
{% for photo in photos %}
<div style="width:100%">
{% for photo in photos %}
<div style="float:left; width:200px; height:200px;">
<img src="{{ photo.photo }}" height="200px" width="200px">
</div>
{% endfor%}
</div>
{% endfor %}
{% endblock content %}
app urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('grid/', views.grid, name='grid'),
]
I am passing in some context. Will it be fixed if I upload the images?
Please give me a solution to this. Thank you.
This happens because you have done two loop. Use only once
They are showing up multiple times because you have a nested for loop. Pick one or the other, but not both, and you will end up with one of each image.
{% for photo in photos %} <-- loop one (for the rows)
<div style="width:100%">
{% for photo in photos %} <-- loop two (for the columns)
<div style="float:left; width:200px; height:200px;">
<img src="{{ photo.photo }}" height="200px" width="200px">
</div>
{% endfor%}
</div>

Am i missing something on templates on django

This is my code on html file on a django project. I am using this code on this function
def home(request):
context = {
'post': posts
}
return render(request,'blog/home.html',context
It does not display anything when I see page source it's just bacis html code head and body empty
<html>
<head>
<title> </title>
</head>
<body>
{% for post in posts %}
<h1>{{post.title}}</h1>
<p>By {{post.author}} on {{post.date_posted}}</p>
<p>{{post.content}}</p>
{% endfor %}
</body>
</html>```
It is a typo. You need to change the context in your view from:
context = { 'post': posts }
to
context = { 'posts': posts }
^^^^^^^

not showing the title in django framework

I'm new to django framework and i'm using VS code
this is view.py file
posts = [
{
'author': 'CoreyMS',
'title': 'Blog Post 1',
'content': 'First post content',
'date_posted': 'August 27, 2018'
},
{
'author': 'Jane Doe',
'title': 'Blog Post 2',
'content': 'Second post content',
'date_posted': 'August 28, 2018'
}
]
def home(request):
context = {
'posts': posts
}
return render(request, 'blog/home.html', context)
and this my home.html file
<!DOCTYPE html>
<html lang="en">
<head>
{% if title %}
<title>Django Blog - {{ title }}</title>
{% else %}
<title>Django Blog</title>
{% endif %}
</head>
<body>
{% for post in posts %}
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
<p>{{ post.authorname }}</p>
<p>{{ post.postdate }}</p>
{% endfor %}
</body>
</html>
the body part works fine but the title doesn't work , i expect to see the title which is blog post one or blog post 2
where is the problem ?
thank you
def home(request):
context = {
'posts': posts,
'title': posts['title']
}
return render(request, 'blog/home.html', context)
But this kind of use is not good in practice. This is your homepage, not a post page. you don't need a specific post's title on the homepage.
I recommend use like that
Create Post model
Create url path for your view function (for post
page)
Create html page for post_page view function
in models.py and don't forget to migrate your model to the databse with python manage.py makemigrations and python manage.py migrate
import django.db import models
class Post(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(
max_length=250,
unique_for_date='publish')
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='blog_posts'
)
content = models.TextField()
date_posted = models.DateTimeField(auto_now_add=True)
# What ever you want you can add
def __str__(self):
return self.title
in urls.py looks like
urlpatterns = [
# your paths what ever you have
path('blog/<slug:post_slug>', views.post_page, name='post_page'),
]
in views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
# and other imports
def home(request):
posts = Post.objects.all()
context = {
'posts': posts
}
return render(request, 'blog/home.html', context)
def post_page(request, post_slug):
post = get_object_or_404(Post, slug=post_slug)
# and other operation you want
return render(request, 'blog/post_page.html', { 'post': post } )
then in your post_page.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ post.title }}</title>
</head>
<body>
<div>
{{ post.content }}
</div>
</body>
</html>
after all I recommend make a base.html then extend your html pages from it
the body part works fine but the title doesn't work
I does - it prints an empty string for the 'title' var because there's no 'title' var in your context, and this is the expected behaviour
i expect to see the title which is blog post one or blog post 2
Why would you expect such a thing ??? If you want your first post's title, use {{ posts.0.title }}. The template engine will NOT try to "guess" anything (hopefully), it just do what you ask for.
where is the problem ?
Well, perhaps passing a value for title in your context might work ?
def home(request):
context = {
'posts': posts,
'title': "This is my beautiful blog"
}
return render(request, 'blog/home.html', context)
Also and FWIW, you can make your template code a bit more DRY:
<title>Django Blog{% if title %}- {{ title }}{% endif %}</title>

CSS fails when passing a list to render(request)

I am trying to follow a tutorial online and for some reason I cannot get css to work correctly with my views.py file and django 2.2. when I remove the "My_context" from return render(request, 'blog/home.html', My_context)
and pass something else like
return render(request, 'blog/home.html', {'title': 'blah') it seems to work just fine.
I have tried restarting the server and and clearing the page cache. I am new to django and not sure what else to try.
views.py
from django.shortcuts import render
posts = [
{
'author': 'xxxxx',
'title': 'Blog Post 1',
'Content': 'My First Post Content',
'date_posted': 'August 27, 2019'
},
{
'author': 'xxxxx',
'title': 'Blog Post 2',
'Content': 'My Second Post Content',
'date_posted': 'August 27, 2019'
}
]
# This function fails to load css correctly
def home(request):
My_context = {
'posts': posts
}
return render(request, 'blog/home.html', My_context)
#This function works fine
def about(request):
return render(request, 'blog/about.html', {'title': 'About'})
home.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<h1>{{ post.title }}</h1>
<p>By {{ post.author }} on {{ post.date_posted }}</p>
<p>{{ post.Content }}</p>
{% endfor %}
{% endblock content %}
about.html
{% extends "blog/base.html" %}
{% block content %}
<h1>About Page</h1>
{% endblock content %}
The major difference between home() and about() is the template you use.
So you should check your home.html contains the path to your css file.
You can also check your console for any error message and share it with us.

Django - passing data with 'include'

I'm a newbie in Django and here's what I want to do: I want to have a base.html that includes a Navigation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
{% include 'nav.html' %}
{% block content %}{% endblock %}
</body>
</html>
pretty simple, but: The navigation should render it's own content flexible, as i want to add a cms later.
<nav class="nav">
{% for item in sites %}
<a class="nav__item" href="{{ item.href.value }}">{{ item.label }}</a>
{% endfor %}
</nav>
I have a render method of index.html (which just extends base.html and adds an h1 tag for testing purposes) like so
def home_view(request, *args, **kwargs):
opts = {
'sites': [
{
'href': {
'value': '/someurl'
},
'label': 'Some Label'
},
{
'href': {
'value': '/lorem'
},
'label': 'Lorem Ipsum'
},
{
'href': {
'value': '/contact'
},
'label': 'Contakt'
}
]
}
return render(request, 'index.html', opts)
but if I run my local server my content does not get passed.
You should use {% include "nav.html" %} inside the {% block content %} tag.
Otherwise it won't be shown.

Categories