Friday, 15 November 2019

How to Build Django eCommerce Web Application?

           
          Django is a web application that comprises bunch of apps. It is a web application has a sub apps of bigger things and has a bunch of components to make the app itself. Django is a tool written in python that used to develop a website. If you look at the  Django website, it describes Django is a high level Python web framework that encourages rapid development in clean and pragmetic design. Web framework is a collection of tools to build a website. Django comes with Object Relational Mapper (ORM) which helps to make a database queries. It has a URL routing which helps to determine what logic to follow depending on the URL of a web request. Another feature is HTML templating which allows us to have presentation logic and insert data into our HTML. It contains a built-in web server for convenience but it is not used outside of the context. When we deploy Django on live website, it works in tandem with web server.
             In order to develop with Django, you need to install the latest version of python3. Once the installation is finished, you can install Django. When you installed python3, it is also installed a script called pip that installs python libraries and tools. You can install django by just typing the command of pip install django==2.2.7. Once you get successfully installed with pytz library which offers timezone support, you are ready to develop a Django project.
Django Files Overview:
           To create a project, just type django-admin.py startproject (projectname), then open that folder in the sublime or Atom text editor and you can see the files and the scripts generated. The manage.py file helps to run various commands for your project. The _init_ file tells python that this folder contains python files. The wsgi or wuzgi file provides a hook for web server. The settings file configure django and url file routes request based on the URL. With these files, you can run the project for the first time. So, just type python manage.py runserver in the terminal and open the browser to see the results. Now, you can see the default screen that Django makes when you create a new project and ready to build completely.

Developing Django App: Django app is a component within an overall Django project or folder with python files. Each Django app has a set of features for a specific purpose. Django app has the features related to forum, wiki, or blog etc., In order to create the app, type the command python manage.py startapp adoptions which will create an adoption app in the terminal.  In the adoptions, there are several files with migration folder. Now, you need to add the Django app to the project. Inside the settings file, you need to add the string of adoptions it installed. The Django has the following types of files and folder that plays an specific role in that application,
   * apps.py - it controls the settings specific to the app
   * models.py - it provides the data layer which the Django uses to construct our database schema and queries.
   * views.py - it defines the logic and control flow for handling request and defines the HTTP responses that are returned.
   * admin.py - it defines the administrative interface of the app. This will allow to see and edit the data
   * urls.py - this will be used for URL routing of the app
   * tests.py - it is used for writing the unit test for the functionality of the app.
   * migrations - this folder uses to migrate the database when you create and change our database schema.

Django Models & Views:
        Django uses a Model View Controller(MVC) architecture. It uses URL patterns, views, models and templates. When Django application receives web request, it uses the URL patterns to decide the views to pass the request for handling. Views provide the logic of the project. It works as a function that takes HTTP request and HTTP response. Each views leverage Django models to perform queries against the database. A Django model is a class with attributes that define the schema or underlying structure of the database table. It has built-in methods for making queries in the tables .Each view leverage templates which help with the presentation layer of the HTML response look like. The template is a separate file consists of HTML along with variables, loops and logic.
     
        URL Patterns   ----------->   Views -----------------> Templates
           (urls.py)                           (views.py)                   (adoptions/templates)                 
                                                       |
                                                       |
                                                       |
                                                  Models
                                                (models.py)
     
         If the request comes into Django with root path of just a slash, it first looks URL patterns to find the view and route the path to functions in adoption/views.py called home. The home function will take the request and make any database calls needed in adoptions/models.py. For ex, htttp://www.ourwebsite.com will be processed as,
   
       /    --------------------->   home ------------------->  adoptions/home.html
(Root Path)
         Models create data layer that create the database structure and query the database. Models.py contains set of models for the django app. Model is a class inheriting from django.db.models. It is used to define fields as class attributes. Model is similar to table in the spreadsheet. Each field of that model is the column for the spreadsheet table and each record in the database is a row in the spreadsheet. To define models fields, you need to define the attributes inside the model by using the fieldClasses with Charfield, or textfield, or integerfield. For each field, you can define the attributes of max_length or blank. To implement the models, open the models.py in the adoptions app. It contains the baseline as from django.db import models. Then, define the class as,

class Dream(models.Model):

   website = models.CharField(max_length = 100)
   mail = models.CharField(max_length = 100)
   name = models.CharField(max_length = 100)
   phonenumber = models.IntegerField()

   class Meta:
      db_table = "dream"

Django Migrations:
        The models define the structure of the database tables. Migrations generate the scripts to change the database structure when we update our code and models. When a new model is defined, the initial migration will create the corresponding database table. Also, the migration is needed when the field is added or removed from an existing model or attributes of the field has changed. The commands in migration are makemigration, showmigration and migrate. Makemigration reads the current model file and inspects the current state of the database to determine the changes need to make the database structure that match the models file. These files are placed in migration folder and numbered starting with one. We can run the migration for the specific app to specific number of migration by,
            Migrate  (appname) number
    Navigate to the folder of manage.py file in the terminal. To make your migration, type python manage.py makemigrations. You can see the output that the adoptions app created the migrations for the models. It is a initial migration, because it does not have the table for these models yet.  You can see the existing migration file by the command of python manage.py showmigrations. To apply the migration, type the command of pyhton manage.py migrate.  You can see the output that the migration applied successfully. The db.sqlite file which helps the database to work. Now, we can see the structure of the database in SQLLite that looks like. Also, you need to run the command of "python manage.py migrate --run-syncdb".  After running the migrations and confirmed that they are applied successfully and ready to use our database.

Django Admin:  It creates an adminstrative interface for our project. In admin.py, you need to import the models by "from .models import ". In order to make an admin interface of this model, you need to inherit the class from admin.modelAdmin. Pass keyword will be used for the valid python class. Then, you need to register this class with the admin to associate the model in it. For ex,

Now, you can see the results in the terminal. Before that, you have to create superuser. So, Just type the command of python manage.py
createsuperuser, set the superuser and password. Once you created the superuser successfully, you can run the project on browser(python manage.py runserver). This will navigate to the admin interface. Now, you can use the superusername and password to the Django admin portal. It lists all the models registered in Django admin.

URL Handlers and Views:  Open the adoptions folder and click on the views file. First, you need to  display the home view. Then, we can display the detail view. To accomplish this, the body of the home view needs to fetch all of the model information. So, we need to import the models and can make query to that models. The HTTP response function will take the responsibility of rendering the HTML on to the template. Also, you can make your view to be concerned with necessary database queries and passing the data to that template.  For ex, the view.py can be defined as,

from django.shortcuts import render
from django.http import HttpResponse

from models import dream

def home(request):
return render(request, 'home.html', {})

Now, we need to create a template folder inside the adoption folder. Inside the folder, we need to create a files for each of our template like home.html, detail.html etc., You may noticed that, if you started the development server, it displays the default welcome page. In order to use your new view, you need to tell the Django to display this view when someone navigates to the home page.  So, update the url.py as,

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

Now, we are ready to test our views which will work.
   


                                                

No comments:

Post a Comment