CSS fails when passing a list to render(request) - python

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.

Related

django: Unable to get sorl-thumbnail working

I am making a django site where users can upload images and I want to use sorl-thumbnail for thumbnail generation and caching. I am using a container based workflow using podman on a fedora silverblue host.
I have setup a memcached cache engine (using the memcached docker image), and can set and get values to and from the cache in django-shell with no issues. I have run the migrate command with sorl-thumbnail added to my installed-apps. I have run the ./manage.py createcachetable command and no errors. I am using pylibmc with:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '127.0.0.1:11211',
}
}
I have created a model which has the sorl.thumbnail ImageField, although I hope to use a standard imagefield eventually, which I believe is possible.
I have the following model, view, and template:
model...
class Image(models.Model):
image_file = ImageField(upload_to=user_directory_path)
#thumbnail = models.ImageField(upload_to=str(user_directory_path) + '_thumb', null=True)
userprofile = models.ForeignKey(ForumProfile, on_delete=models.CASCADE, related_name="images")
view...(the get function is added during debugging this issue)...
class ForumProfileUploadView(LoginRequiredMixin, FormView):
form_class = ImageForm
template_name = 'list.html'
success_url = reverse_lazy('my-view')
def get(self, request, *args, **kwargs):
form = self.form_class()
message = 'Hi!'
images = Image.objects.all()
context = {'images': images, 'form': form, 'message': message}
return render(self.request, 'list.html', context)
def form_valid(self, form):
obj = form.save(commit=False)
obj.userprofile = self.request.user.profile.forumprofile
# img = PillowImage.open(obj.image_file.file)
# obj.thumbnail = MakeThumbnail(self.request.FILES['image_file'])
# breakpoint()
obj.save()
message = 'Success!'
images = Image.objects.all()
breakpoint()
context = {'images': images, 'form': form, 'message': message}
return render(self.request, 'list.html', context)
def form_invalid(self, form):
message = 'The form is not valid. Fix the following error:'
images = Image.objects.all()
context = {'images': images, 'form': form, 'message': message}
return render(self.request, 'list.html', context)
template...
<!DOCTYPE html>
<html lang='en'>
<head>
</head>
<body>
<!-- List of uploaded documents -->
{% block content %}
{% load thumbnail %}
{% if images %}
All images in the database:
{% for image in images %}
{% thumbnail image.image_file.url "100x100" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
{% endfor %}
{% else %}
<p>No images.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url 'my-view' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ message }}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.image_file.label_tag }} {{ form.image_file.help_text }}</p>
<p>
{{ form.image_file.errors }}
{{ form.image_file }}
</p>
<p><input type="submit" value="Upload"/></p>
</form>
{% endblock content %}
</body>
I have managed to get it working. I am fairly certain that the necessary thing was for me to set the cache to work for the entire site, although I could have used it for a specific view, and this allowed sorl.thumbnail to start working.
https://docs.djangoproject.com/en/3.1/topics/cache/#the-per-site-cache

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>

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>

Automatically Display POST data Django

Goal:
Display POST data on Django-based website as it is received via webhooks from Github
If possible, to continually append new events one after the other on the website
Where I'm at:
I have the github POST data, I can print it on the terminal, but cannot display on my html page.
Currently a beginner with Django but any advice would be much appreciated!
Here's a peak at my views.py:
#csrf_exempt
def home(request):
if request.method == "POST":
event = request.META['HTTP_X_GITHUB_EVENT']
body = json.loads(request.body)[event]
context = {
'event': event,
'body': body,
}
print(context)
return render(request, 'home.html', context)
return render(request, 'home.html')
Here is my home.html
{% extends "base.html" %}
{% block content %}
<div>
<h3><b>fudge</b></h3>
{% if event %}
<p>Event: {{ event }}</p>
<p>Body: {{ body }}</p>
{% endif %}
</div>
{% endblock %}
Ideally, I'd like to re-render my home.html page as soon as a POST is received, but don't know how to keep it persistent. As for my urls.py, I only have ^$, views.home, name='home'. Let me know if you'd like to see anything else!

print list of dictonaries to template

this may be silly question, But newbie here, need some help
I need to print dictionary to template
template_var = {}
settings = Article.objects.filter().values('title','content')
for some in settings:
pprint.pprint(some)
the output of console log is
{'content': u'add blog ', 'title': u'blog here'}
{'content': u'fweferwgfwefw', 'title': u'few'}
{'content': u'fsvbfsvbsfvsdfv', 'title': u' fsfsbfsbvsfvb'}
this is the way i am passing some to template_var['article']= some. And in my html i do like this
{% for content in some %}
{{ content }}
{% endfor %}
but that's not working.
You're iterating settings in the for statement:
for some in settings:
pprint.pprint(some)
But, the view code is passing some instead of settings to the template, and iterating it. In addition to that, the code is passing the variable as article, but it is used as some in the template.
Make them to be consistent:
view
template_var['settings'] = settings
template
{% for some in settings %}
{{ some }}
{% endfor %}
If you want to print the dictonary to templates the you can do
in viwes.py
return render(request, "template.html", { 'settings' : settings})
and in template.html
this is for getting entire dictonary
{% for set1 in settings %}
{{set1}}
{% endfor %}
and this is for getting each element of dictonary
{% for set1 in settings %}
{{set1.content}}<br/>
{{set1.title}}
{% endfor %}

Categories