Create Template and Connect to Model - koglak/SWE573 GitHub Wiki

1) Create a new directory path for views.

A template is a file that we can re-use to present different information in a consistent format.

blog>templates>blog

2) Create a post_list.html in blog directory.

image

3) Copy the html code in post_list.html

<!DOCTYPE html>
<html>
    <head>
        <title>Ola's blog</title>
    </head>
    <body>
        <p>Hi there!</p>
        <p>It works!</p>
    </body>
 </html>

4) Save your file and run it locally.

 python manage.py runserver

image

5) Save your changes in github and later control your github account!

 git add .

 git status

 git commit -m "html is added"

 git push

6) Run your website via PythonAnywhere! Open PythonAnywhere bash console and write below codes!

 cd ~/koglak.pythonanywhere.com

 git pull

image

7) Connect Model and Template

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

8) Make visible your 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 %}

9) Run it on server!

 python manage.py runserver

10) Save it to github!

 git status

 git add .

 git commit -m "template and model are connected"

 git push
⚠️ **GitHub.com Fallback** ⚠️