-I’ll be using VScode for building up my Django-Project -The integrated terminal really helped me in this

These django steps would be with respect to the steps I followed in order to learn Django and create my very own blog

SETTING UP VIRTUAL ENVIRONMENT FOR USING DJANGO

  1. First of all install a virtual environment for using Django.
  2. Activate the virtual environment using . env/bin/activate

CREATING FOLDER FOR STORING YOUR DJANGO PROJECT

  1. Make a folder that should contain your project.. FOR EG: Folder named "BLOG"

STARTING WITH YOUR DJANGO-PROJECT

Reference- Video2 of Django Playlist of The Net Ninja:

  1. Move to your required folder .. cd Blog
  2. Type the following command in the terminal django-admin startproject projectname - This would create a folder named foldername with required materials present in it
FOR EG: django-admin startproject BlogMaterials
  1. Move into your folder created using django-admin startproject say “BlogMaterials” using cd foldername
  2. RUN-SERVER You can create your own server and view your project-works over there
    Run : python manage.py runserver

USING URLs and Views File in your Django-Project folder

Reference- Video3 of Django-Playlist of The Net Ninja

  1. Create a file named views.py in the folder containing your urls.py file We can add html links to our project in the urls.py and the respective functions to be rendered by clicking them in our views.py file

  2. Add urls to your urls.py file Firstly import views by typing : from. import views in your urls.py file

     FOR EG: path('about/',views.about), : The "about" link would be created and about function would be requested when clicked over it 
    
  3. Define your required function in the view.py file Firstly import the following files : Type “from django.http import HttpResponse” in view.py file

    FOR EG : 
    def about(request):
            return HttpResponse("about") 
    

    The above function prints “about” on the page when request is sent to the required page

  4. Run server and view your project so far Code : python manage.py runserver

USING HTMLTemplates in urls.py and views.py file

Reference- Video4 of Django-Playlist of The Net Ninja

  1. Create a “templates” folder in the main folder that is “BlogMaterials”.
  2. Add homepage.html and about.html in this “templates” folder and add html content in it which you want to be displayed over the browser
  3. Add path of template folder in settings.py file. Open settings.py and move to the section named TEMPPLATES Under the TEMPLATES section add the relative path of your template folder in “DIRS” part // It will look under temmplate folder of each app
  4. Change the respective functions in views.py file FOR EG : Firstly import the following in your views.py files
    from django.shortcuts import render
    def about(request):
            return render(request,'about.html)    
  1. Run server to and view the respective changes

Using Django Apps

Reference- Video5 of Django-Playlist of The Net Ninja

  • MAIN FRAMEWORK :
    • Django project
      • Djangonautic Apps
      • articles app
      • accounts app
        ( BlogMaterials)
  1. Run:
python manage.py startapp articles
  • This creates articles folder along with required files
  1. Register this articles folder in the settings.py file in the main folder under the INSTALLED_APPS section
  2. Create urls.py file in articles folder in the main folder of Django Project You can copy paste your urls.py file in this articles folder as well. Remove the lines containing admin from the urls.py file in this folder as those are not required
  3. Create a template folder in this main articles folder and create another aricles folder under this template folder . Store your respective html files in this folder say : article_list.html
  4. Add path of urls.py file of abouts folder in the urls.py file of your main folder(“BLogMaterials”) so that the server knows that the urls.py file of articles file could be used EG : Add the following code in path : Firstly import “include” using the following code :
from django.conf.urls import url,include

Then under the urlpatterns section write the following code :

path('articles/',include(articles.urls)),
  1. In the views.py file of the articles folder define the functions that we want to get rendered EG :
def article_list(request):
        return render(request,'articles/article_list.html')
  1. Run the server and view the necessary changes

MODELS

Reference- Video6 of Django-Playlist of The Net Ninja Models : It contains the tables and names that are to be displayed in the database

  1. Open models.py file in the articles app and make a class in there. FOR EG:
    class Articles(models.Model):
            title=models.CharField(max_length=100)
            slug=models.SlugField()
            body=models.TextField()
            date=models.DateTimeField(auto_now_add=True)

MIGRATIONS

Reference- Video7 of Django-Playlist of The Net Ninja Connects the database and the models.py file

  1. Firstly migrate unmigrated files by running the following commands : python manage.py migrate
  2. Create a migration file that will store changes related to migrations(made by us)
    Create it running the following command: python manage.py makemigrations — This creates a 0001_initial.py file under migrations folder in articles app folder
  3. To migrate the migrations made by us , run the following command: python manage.py migrate
    — This moves the model to database

USING DJANGO ORM

Reference- Video8 of Django-Playlist of The Net Ninja This helps to interact with the database

  1. Run python manage.py shell
  • Opens up an interactive shell to interact with the database using django codes
  1. Firstly, we would need to import Articles in shell using the following command:
from articles.models import Articles (from outer folder name.model file name import Class_Name)

30)Some commands to be used in the shell

  • Articles.objects.all() // Lists the articles present in the database
  • Create a new Article using the following command in shell article = Articles()
  • Input the title in the article using the following command article.title = “hello world”
  • save this article to the database using the following command- article.save()
  • Various articles created manually are stores in the form of arrays - For EG: To access the first article run the following command - Articles.objects.all()[0]

// Inorder to show the title pf the article objects in ORM : -: Open the models.py file -: add the following function under the class of Articles-

def __str__(self):
   return self.title

USING DJANGO ADMIN

Reference- Video9 of Django-Playlist of The Net Ninja — Used to fill database and control usage of our model

  1. Create the admin user(super user) using manage.py Run the following command - python manage.py createsuperuser
enter your details : User Name : abc
                     Email ID  : xyz@gmail.com
                     Password  : xxx
  1. In order to view your articles in the admins page, we need to register it in the admins.py file under articles app Firstly import the following -
from .models import Articles
admin.site.register(Articles)
  1. Run the server and go to the admin webpage
  • We can see all other staff members registered under here along with the super user(green tick user) and our articles etc as well.

INSERTING PYTHON CODES IN HTML TEMPLATES USING TEMPLATE TAGS

Reference- Video10 of Django-Playlist of The Net Ninja

  • We want to dynamically input all the articles in the models.py file to our webpage
  • Template tags are use to use python codes in out html files
  • In html files we use {% %} for writing codes and {{ }} for outputting any data
  1. Under the views.py file import Articles class from models.py file using the following code -
    from .models import Articles
  1. Under the article_list function, pass the class Articles as a dictionary so that it can be used in the asrticle_list template
FOR EG: 
        def article_list(request):
                # order all the articles present in the database by date 
                list_of_articles = Articles.object.all().order_by("date") 
                return render(request,'articles/article_list.html',{"articles":list_of_articles})
  1. Open article_list.html under the templates folder in articles app
  2. In the article_list.html we can use {% %} for writing python codes and ({ }) for outputting any python code — Iterate through the dictionary_of_articles passed and print title,vody and date of each article using the following code in the body tag of html file
    <div class="articles">
        {% for article in dictionary_of_articles %}
                <div class="article">
                        <h2> a href="#"> {{ article.title }} </a> </h2>
                        <p> {{ article.body }} </p>
                        <p> {{ article.date }} </p>
                </div>
        {% endfor %}
    </div>
  1. Run the server and view the necessary changes made

USING MODEL METHODS

Reference- Video11 of Django-Playlist of The Net Ninja We dont want to list complete information over the articles page at one go

  1. Open the models.py file under the articles folder and define the following function to display the first fifty characters on the articles webpage
def snippets(self):
        return self.body[:50] #dislpays the first fifty characters over the Blogs first page
  1. In the article_list.html in the templates folder of the articles app, instead of printing article.body print article.snippets

Working with static files that is css files etc

Reference- Video12 of Django-Playlist of The Net Ninja

  1. We can allow Django to save our staticfiles In the urls.py file under the BlogMaterials folder, add the following code - Firstly import the following
    -from django.contrib.staticfiles.urls import staticfiles_urlpatterns
        #Then write the following below url_patterns 
    urlpatterns += staticfiles_urlpatterns()
  1. In the settings.py file Under the “STATIC_URL” value static would be present
  • Now you can find your static files over the webpage . FOR EG: style.css can be found over ..../static/style.css
  1. In the settings.py file add STATICFILES_DIRS at the bottom(just below STATIC_URLS) and write the following there
  • firstly import os in settings.py file then,
    STATICFILES_DIRS=(
            os.path.join(BASE_DIR,'assets'), #Join the base_dir ectory(here BLogMaterials) and the assets folder containing the static files
    )
  1. Create a folder named assets under your base directory(BlogMaterials) and enter static files such as styles.css over there
  2. In order to connect this styles.css with the articles_list.html connect it using
    <link rel = "stylesheet" href="/static/styles.css">
  • A better way to load styles.css or other staticfiles in the html file is using the templates tags
Write 
        {% load static %}
        # above Doctype(at top of html file)
        # Then ,write the following
      <link rel = "stylesheet" href="{% static 'styles.css' %}">
  • This will ensure that whenever the directory for staticfiles are changed we dont have to re write the directory name at every required place
  1. Build up your styles.css file and run server to view the changes made

Extending template tags to be used in combining html files

Reference- Video13 of Django-Playlist of The Net Ninja

  1. Create a base_layout for html files which is to be used by all other html files in the main directory(BlogMaterial/templates) – Open the templates folder under articles and create a base_layout html file with template tag as shown below. All other html files should only start and end at the area between these template tags eg :
    {% load static %}
    <!DOCTYPE html>
    <html>

    <head>
            <title>ARTICLES</title>
            <link rel = "stylesheet" href="{% static 'styles.css' %}">
    </head>

    <body>
            <div class="wrapper">
                    {% block content %}
                    {% endblock %}
            </div>
    </body>

    </html>
  • Now all other html files will have this basic tempplate if it uses it eg :
Articles_list.html in artilces/templates folder
        {% extends 'base_layout.html' %}
        {% block content %}
                <h1>ARTICLES LIST</h1>
                <div class="articles">
                        {% for article in dictionary_of_articles %}
                                <div class="article">
                                        <h2>
                                                <a href="#">
                                                        {{ article.title }}
                                                </a>
                                        </h2>
                                        <p>
                                                {{ article.snippets }}
                                        </p>
                                        <p>
                                                {{ article.date }}
                                        </p>
                                </div>
                        {% endfor %}
                </div>
        {% endblock %}
  • We need to mention the above mentioned template tag if we want to extend it from the base_layout.html
    {% extends 'base_layout.html' %}
  • The extended code is written between two template tags that is {% block content %} and {% endblock %} which also present in the base_layout.html file

Using url parameters and RegeX

Reference- Video14 of Django-Playlist of The Net Ninja

  1. In views.py file under articles folder define function to see the article response after importing HttpResponse from django
    from django.http import HttpResponse
    def article_details(request,slug):
    return HttpResponse(slug)
  1. In urls.py file under the articles folder under the urlpatterns section write the following code
    re_path(r'^(?P<slug>[\w-]+)/$', views.article_detail),
    # after importing repath from django
    #  We can also use regex instead : 
    re_path(r'^(?P<slug>[\w-]+)/$', views.article_detail),

NAMED URLs(URL TAGS and URL NAMES)

Reference- Video15 of Django-PLaylist of The Net Ninja Changing the links to which the page directs on clicking a respective article.: This is done using named URLs.

  1. Under the urls.py file in the articles folder add names to the respective urls
    # contains the index page in #articles 
    path('',views.article_list, name="list" ), 
    # re_path(r'^(?P<slug>[\w-]+)/$', views.article_detail),
    re_path(r'^(?P<slug>[\w-]+)/$', views.article_detail, name="detail"),
  • Also, add a namespace above say app_name = 'articles' as this will prevent the names list and details to be used by different urls.py file
  1. Under the base_layout.html(in Templates folder) within the wrapper code add the following line,
   <h1> <a href="{% url 'articles:list' %}"><img src="{% static 'logo.png' %}"</a></h1>
  1. Under the article_list.html in articles folder , add the following line (replacing #)
    Replace # with "{% url'articles:detail' article.slug%}"
  1. Run the server to view the changes made