Djangoでstaticフォルダを作ってhtmlやcss等の静的ファイルを出力する方法

スポンサーリンク

前回の記事では、Django のテンプレートについて説明しました。

さて、この記事では、もう一つの似たようなトピックである Django の静的ファイルについて学ぶつもりです。

さて、例えば facebook.com のような Web サイトに行くと、Web ページにはテキストだけでなく、様々な絵や色が表示されます。

さて、フロントエンドでは、完全な Web ページを構成するこの美しいビューは、通常 CSS(Cascading style sheets) や JavaScript ファイル、そして画像を使って実現されています。

これらの画像、CSSファイル、JSをすべてstaticというフォルダに格納し、そのファイルを静的ファイルと呼びます。

スポンサーリンク

Django の静的ファイルフォルダを作成する

前回の記事で学んだ Templates と同じように、Django の静的ファイルも static という名前の別フォルダに保存されます。

Django の apps ディレクトリに static フォルダを以下のように作成します。

body{
    background: white url("images/books.jpg") no-repeat;
}

名前付き静的ファイルフォルダ

Templatesのチュートリアルと同様に、静的ファイルにもNamespacingが必要です。

ここでも、 Static ディレクトリの中にアプリ名を追加する必要があります。

これは、 Django が (インポート/ロード時に) ファイルを検索するためのショートカットを使うためです。

<html>
    <head>
        <p> Headeer Information </p>
    </head>
     
    <body>
        <p> Main Text Code </p>
    </body>
     
</html>

静的ファイルをリクエストすると、Django は INSTALLED_APPS/settings.py を順次検索し、最初の結果を返します。

apps フォルダに同じ名前の静的ファイルが 2 つある場合、Django は間違ったファイルを返すかもしれません。

従って、前回の記事のように、以下のスクリーンショットのように、静的フォルダの中に新しいフォルダ () を追加してください。

<head>
   <link rel="stylesheet" type="text/css" href= "{%  static 'books_website/style.css' %}">
</head>

Webページ用のシンプルなCSSファイルを作成する

では、簡単な CSS ファイルを作成し、 Django がそれをどのように Web ページに読み込むかを見てみましょう。

私たちの第一の焦点は Django を学ぶことなので、 CSS で書かれたコードを理解できなくても気にしないでください、ということに注意してください。

1. ページに背景画像を追加する

CSSを使って、ウェブページ(ホストサイト/書籍)に背景画像を追加してみましょう。

Webページで使用する画像は、static/フォルダの下にあるimagesという別フォルダに保存することが望ましいです。

注:別フォルダーというのは、staticフォルダー内に作成したフォルダー内にという意味です。

下の画像で、ディレクトリ構造を確認することができます。

{% load static %}

images」フォルダを作成し、そこに下の画像を保存します。

{% static "books_website/styles.css%}

2. 静的ファイルで「BookView」ビューのCSSコードを書く

そろそろ、画像を背景として表示するコードを書きます。

背景を表示するためにCSSを使用することにします。

コードの意味は気にせずコピーしてください。

下の画像にあるファイル名を変更することを確認してください。

python manage.py runserver

CSSの文法はわかりやすいので、試してみれば何をしようとしているのかがわかると思います。

というわけで、基本的には以下の通りです。

  1. 目的:ウェブページの背景を変更します。
  2. background: white は、何らかのエラーで画像が読み込まれない場合に備えて、ウェブページに白い背景色を表示することを意味します。
  3. URL(“images/books.jpg”)は、使用するイメージのパスです。
    1. No-repeat: ブラウザのウィンドウが画像サイズより大きい場合、画像が繰り返されないようにすることを示します。

3. 静的ファイルを取り込むためのテンプレートファイルの修正

次に、templates フォルダで、”BookView” ビューとリンクしているテンプレートを開いてください。

私の場合、それは BookView.html です。

前回の Django Templates の記事では、最終的に BookView.html を作成しました。

{% load static %}
<html>
 
<head>
   <link rel= "stylesheet" type="text/css" href= "{%  static 'books_website/style.css' %}">
</head>
 
<body>
    {% block content %}
 
    <h3>{{book.title}}</h3>
    <h4>{{book.price}}</h4>
    <h5>{{book.genre}}</h5>
     
    {% endblock %}
 
</body>
 
</html>

これが基本的な HTML のファイル構成です。

もし、あなたが HTML を使ったことがなければ、試してみてください。

HTML はかなり基本的な言語なので、2、3 時間で習得できます。

Static
Static

HTMLファイルの正しい構文を身につけるために、HTMLファイルを修正してみましょう。

その結果、以下のようなファイルになります。

INSTALLED APPS
INSTALLED APPS

4行目にあったインクルード行を削除し、直接「Books Hub」というヘッダーに置き換えている。

次に、CSSファイルをリンクさせるために、

Namespacing Static
Namespacing Static

ここです。

  • 目的:CSSファイルをHTMLファイルにリンクさせる
  • <link: (css=”” *=””
    Static directory Structure
    Static directory Structure

    4. Adding the {% load static %} line to the HTML file

    If you now try to run the server, you will get an error when you enter this url – http://127.0.0.1:8000/books/.

    Books
    Books

    You will notice, that the webpage is unable to load the path of the CSS file, we added in our HTML file.

    This is because we didn’t load the static tag for our static file. That is, if we don’t load static tags, then Django won’t know what the word “static” used below means.

    The line below searches for the path of the static folder and then loads it up.

    BookView Inclusion 2
    BookView Inclusion 2

    So when we use the below code, Django knows what the word static refers to.

    BookView HTML
    BookView HTML

    After adding the {% load static %} line. The file will now look like

    BookView HTML
    BookView HTML

    Note: Always keep the Template inheritance line at the top. This is because the BookView.html file is an extrapolation of the base file (basic.html) present in the project directory.

    So before Django reads this file, it should first read the inherited file.

    Now save the BookView.html file. The server should reload itself. If not, use the command below in the shell

    Error
    Error

    And there you go! We have the background image is added to the webpage.

    BookView HTML
    BookView HTML

    Similarly, create a BookIDView.html for the 127.0.0.1:8000/books/ endpoint:

    Browser 1
    Browser 1

    Here we are using the same background image, therefore the link attribute for the CSS file remains the same.

    Try to understand on your own for better learning, and if you have any doubts go to Django Templates’ article to understand

    Lets run this webpage as well and check

    Browser 2
    Browser 2

    Conclusion

    That’s all for the Django static files tutorial! We hope you have gained sufficient knowledge about static files and their use in Django. Also, you can learn more about the Django Static files from the official documentation.

    Stay tuned for more advanced tutorials on Django topics!

タイトルとURLをコピーしました