Create a View
Go tp polls/views.py
Bring the model from .models import Question, Choice
Create a view to get and show questions (in the same file views.py)
def index(request):
return render(request, 'polls/index.html')
Create the URLs
In polls folder create urls.py file
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index')
]
In the main app folder, oper urls.py file and include the file you created
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
In setting.py 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 manage.py 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 %}
POLLS
{% endblock %}
Creating partials files for navbar and footer to make the base file cleaner
- In the templates’ folder create a folder and call it partials
- Create partial files in it, they must start with _ for example _footer.html
- 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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'btre/static')
]
4. Run python manage.py 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’ %}”>