1. Setting Up the project
Django is Powerfull! for setting it up first open terminal or cammand prompt and run the following commands.
pip install django
Now navigate to the directory for your blog and create django project for it.
django-admin startproject blog
Navigate to newly created Project folder.
cd blog
you have successfully created the Django Project!
Creating the First app for project
start your first app named post
python manage.py startapp post
this will create a new directory within Project Folder. This manage.py file is the main controller of the project.
Open Your project in any code editor. For e.g. VS Code! If VS Code is installed in your system then just type
code .
in your Project Directory and the Project Directory will Open in New VSCode Window
Now we have to install this Post app in out Blog Project.
# blog/settings.py
# code
INSTALLED_APPS =[
# APPS ,
post, # add to app list
]
# code
Now we have to create the urls.py
file in post
app for managing all the urls of post
app and include this urls.py
URLs of Post App with main urls of our Blog Project.
# blog/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("posts/", include('post.urls')), # added
]
The Basic concept for Displying Data on page for user is, first create view than assign that view to url route. For this lets create our first view and url for it.
# post/views.py
from django.shortcuts import render
def index(request):
context = {'name': "Darksied",}
return render(request, 'index.html' , context )
Here, the function based view will return the template html file name index.html . The Template files can be stored in templates folder within the app.
<!-- post/templates/index.html -->
<html>
<head>
<title>{{ name }} | Blog</title>
</head>
<body>
<h1>Hello {{ name }}! </h1>
</body>
</html>
Now, we have to set url for our index view.
# post/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name='index'),
here, the views has been imported and path will assign the view to url "" which is blank means that it will serve at /
route of posts. Means at https://127.0.0.1:8000/posts/
your will view the index View.