Django Build Front Facing Page Django.How

Author avatar wrote on 26/05/2022

Create a View

Go tp polls/

Bring the model from .models import Question, Choice

Create a view to get and show questions (in the same file

def index(request):
    return render(request, 'polls/index.html')

Create the URLs

In polls folder create file

from django.urls import path

from . import views

app_name = 'polls'

urlpatterns = [
    path('', views.index, name='index')

In the main app folder, oper file and include the file you created

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),

In file define the new path under templates, DIRS

'DIRS': [os.path.join(BASE_DIR, 'templates')],

Now when the requested url is /polls the file we create it will control the behavior

Create the HTML file

In the main app folder create a folder template, create a folder inside call it polls, then create index.html file

Restart the server, Control + C then python runserver

Create Base Template File

In templates/polls folder create base.html

Extend the files you want to use like index.html

{% extends 'base.html' %}
{% block content %}
{% endblock %}

Creating partials files for navbar and footer to make the base file cleaner

  1. In the templates’ folder create a folder and call it partials
  2. Create partial files in it, they must start with _ for example _footer.html
  3. Extend the base file or any other file to include the partial {% include ‘partials/_navbar.html’ %}

Adding Static Files like CSS, JS & Images Files

1. In the project main folder create a folder static

2. Add the files and folders you want to use to this folder

3. Go project settings file

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
    os.path.join(BASE_DIR, 'btre/static')

4. Run python collectstatic a static folder will be created in project folder root

5. Declare the resources you want to include in your files, for example, base.html file

  • In the top of the file add {% load static %}
  • Fix links <link rel=”stylesheet” href=”{% static ‘css/all.css’ %}”>