not showing the title in django framework - python

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>

Related

Global variable doesn't work inside django views

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',
},
]

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 }
^^^^^^^

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 - Models does not call content of database

I have created a class in the models.py containing the information of articles I want to insert in a website
from django.db import models
from django.urls import reverse
class Article(models.Model):
"""
Model representing an article.
"""
title = models.CharField(max_length=200)
authors = models.CharField(max_length=200)
summary = models.TextField(max_length=1000, help_text='Enter a brief description of the article')
content = models.TextField(max_length=100000)
def __str__(self):
"""
String for representing the Model object.
"""
return self.title
def get_absolute_url(self):
"""
Returns the url to access a detail record for this article.
"""
return reverse('article-detail', args=[str(self.id)])
After that, I have inserted an article using the admin panel of Django and saved it.
Then, I have created the index.html shown below calling the articles in the database
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}{% endblock %}
</head>
<body>
{% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
{% block content %}<!-- default content text (typically empty) -->
<!-- Articles -->
<div class="articles">
<h1>Titolo: {{ article.title }}</h1>
<p><strong>Autori:</strong> {{ article.authors }}</p>
<p><strong>Riepilogo:</strong> {{ article.summary }}</p>
<p><strong>Testo:</strong> {{ article.content }}</p>
</div>
{% endblock %}
</body>
</html>
But the article is not shown despite being in the database (see prints below)
EDIT1: inserted views.py as requested
from django.shortcuts import render
from .models import Article
# Create your views here.
def index(request):
"""
View function for home page of site.
"""
# Render the HTML template index.html with the data in the context variable
return render(
request,
'index.html',
)
You are not including any articls in your template context:
return render(
request,
'index.html',
)
You could include the articles in the template context with:
articles = Article.objects.all()
return render(
request,
'index.html',
{'articles': articles}
)
Then in the template you need to loop through the articles.
<!-- Articles -->
<div class="articles">
{% for article in articles %}
<h1>Titolo: {{ article.title }}</h1>
<p><strong>Autori:</strong> {{ article.authors }}</p>
<p><strong>Riepilogo:</strong> {{ article.summary }}</p>
<p><strong>Testo:</strong> {{ article.content }}</p>
{% endfor %}
</div>

Django form not submitting

Recently, I've been working on a project to make certain tasks that are crucial to a project I am a part of become a lot easier.
The form was working the last time I checked it (a month ago). Since then, I moved it off of my computer and on to a server. The form is no longer submitting.
#forms.py
from django import forms
from .models import OnlineEssay, HardCopy, FaceToFaceConference
class OnlineEssayClientForm(forms.ModelForm):
class Meta:
model = OnlineEssay
fields = [
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"client_email",
"feedback_primary",
"feedback_secondary",
"essay_file",
]
labels = {
'client_first_name': ('First Name'),
'client_last_name': ('Last Name'),
'client_grade': ('Grade Level (As Number)'),
'client_teacher': ('Teacher'),
'client_email': ('Email Address'),
'feedback_primary': ('I need/would like feedback on:'),
'feedback_secondary': ('And,'),
}
class OnlineEssayTutorForm(forms.ModelForm):
class Meta:
model = OnlineEssay
fields = [
"essay_type",
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"client_email",
"feedback_primary",
"feedback_secondary",
"essay_file",
"essay_tutor",
"essay_feedback",
]
class HardCopyTutorForm(forms.ModelForm):
class Meta:
model = HardCopy
fields = [
"essay_type",
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"feedback_primary",
"feedback_secondary",
"essay_tutor",
"essay_feedback",
]
class FaceToFaceConferenceTutorForm(forms.ModelForm):
class Meta:
model = FaceToFaceConference
fields = [
"essay_type",
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"feedback_primary",
"feedback_secondary",
"essay_tutor",
"essay_feedback_notes",
]
<!-- templates/submit.html -->
{% extends 'base.html' %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% block head_title %}Welcome{% endblock %}
</head>
<body>
{% block content %}
<h1>Submit Your Essay</h1>
<div class="bs-callout bs-callout-default">
<p>Fill Out The Form Below, then press Submit</p>
</div
<form method="post" enctype="multipart/form-data">{%csrf_token%}
{{form|crispy}}
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
{% endblock %}
</body>
</html>
#views.py
from django.shortcuts import render
from django import http
# Create your views here.
from .forms import OnlineEssayClientForm
def submit(request):
form = OnlineEssayClientForm(request.POST or None, request.FILES or None)
context = {
"form": form,
"page_title" : "Submit Your Essay",
}
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/success/')
return render(request, "submit.html", context)
It was actually a pretty simple issue. I had forgot to close the </div> tag at the end of the callout. The form submits fine now.

Categories