Create Template and Connect to Model - koglak/SWE573 GitHub Wiki
A template is a file that we can re-use to present different information in a consistent format.
blog>templates>blog
<!DOCTYPE html>
<html>
<head>
<title>Ola's blog</title>
</head>
<body>
<p>Hi there!</p>
<p>It works!</p>
</body>
</html>
python manage.py runserver
git add .
git status
git commit -m "html is added"
git push
cd ~/koglak.pythonanywhere.com
git pull
Views are connect models and templates. Model is in model.py
file and template is post_list.html
file. view.py
is used to connect template and model.
Open blog>views.py and edit code as below. posts is defined to filter objects and ordered by publish date. posts is passed to render function call.
from django.shortcuts import render
from django.utils import timezone
from .models import Post
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
Now model and template is connected. We can show model in our template by editing html file. Django template tags is used to Python-like codes into HTML.
{% for post in posts %}
<article>
<time>published: {{ post.published_date }}</time>
<h2><a href="">{{ post.title }}</a></h2>
<p>{{ post.text|linebreaksbr }}</p>
</article>
{% endfor %}
python manage.py runserver
git status
git add .
git commit -m "template and model are connected"
git push