Welcome to the third part of the web application development guide in Django.
Repository
https://github.com/Polianek/django-tutorial
What Will I Learn?
In this article, we will create the first template and connect css to this template using static files.
Requirements
- Installed django (>= v. 2.1)
Difficulty
Basic
Tutorial Contents
First thing, let's connect the index.html template to the view. Change
return HttpResponse('Hello world!')
into
return render(request, 'sockshub/index.html')
. Your code in the views.py file should look like this:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, 'sockshub/index.html')
Now create a tree in the project folder named 'sockshub'. templates/sockshub/index.html
Now open the file index.html created a moment ago and enter the paste there:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Socks photos stock</title>
</head>
<body>
<div id="navbar">
<ul>
<li>Home</li>
<li>Gallery</li>
</ul>
</div>
<div id="container">
My favourite socks: img
</div>
</body>
</html>
As you can see, the page reads the file correctly :) Now it's time to add some css - we will use the static file.
Create a new project with the command django-admin createapp personal
while in the main application folder (where the manage.py file is located).
Now add 'personal' to INSTALLED_APPS in settings.py.
If you have the application turned on all the time, you will notice that after saving settings.py you will see a folder migrations in personal - that's good.
Create the tree, this time in the personal folder. static/personal/sockshub.css
Return to index.html and paste this in the 'head' tag:
{% load static %}
<link href="{% static 'personal/sockshub.css' %}" rel="stylesheet">
and edit the previously created sockshub.css file according to your own idea. Because of the lack of artistic talent i did it like this:
html, body{
background: salmon;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
position: relative;
}
ul, li, ol{list-style-type: none; margin: 0;}
#navbar{
top: 0;
width: 100%;
height: 35px;
border-bottom: 2px solid #333;
background: aquamarine;
}
#navbar > ul > li{
float: left;
width: 5vw;
line-height: 2;
}
If you have an application running, you must restart it to load static files correctly.
That's it. Have fun with your app ;)
Curriculum
- #1 | Installation and first configuration of the django app - Django tutorial
- #2 | Hello world. Setting views.py and urls.py, configuring settings.py - Django tutorial
Proof of Work Done
In the next article I will describe models and admin panel, Cya.
This post has received a 8.26 % upvote from @boomerang.