Introduction to Django - Online Shopping Website

 


DJANGO is an open source and free Python Web framework. Framework is a library of reusable modules. It defines a structure for our application.

There are lots of popular websites built with Django such as Instagram, Youtube, Pinterest. For more information about popular websites, click here!


NOW IT'S PROJECT TIME !

NOTE: You can find the project in my GitHub repo.

Creating Django Project

  1. Create a python project.

  2. Install django library. 

    1. Pip install django==2.1

  3. Create a django project.

    1. Django-admin startproject pyshop .

  4. Run development web server.

    1. Python manage.py runserver

Creating Apps

Apps are functional areas in our project like “product management” or “customer management”. Each app is a python package.

  1. Create an app package

    1. Python manage.py startapp products

We created a package called “products”. We’ll use this app as our product management function.

Creating Views For Apps

View is basically a function that gets called by Django when the user navigates to a particular page. How it works:

  • We navigate to a page “.../products”

  • Our browser sends an http request to our web server

  • Django takes this request and sends it to our view function

  • In this request, we can find information about the client


  1. Define what the user will see on the “Views” file. Simply we define a function.

URL Mapping

Django doesn’t know that it should call the “index” function when we send a request to “/products”. We need to map “(URL) /products” --> “(FUNCTION) index”. It's called “URL Mapping”!

URL means “Uniform Resource Locator” and basically “Address”.

  1. Create a “urls.py” file in the app package. Naming is important, urls is a convention in Django. We need to follow this convention to structure our project.

  2. Define “urlpatterns” variable in urls file. It's also a convention.

  1. Map the function to the corresponding URL. Use “urls.py” module in our products app.

    1. /products --> index: We remove the root of the url “/products”.

    1. path('', views.index)

  1. In the last part, we need to tell Django about our app “products”. Up to this point, Django is not aware of this app. Edit “urls.py” in our pyshop project and map it to the app's url.

    1. path('products/', include('products.urls'))

Creating Models For Apps

Models are a representation of a real world concept. In an online shop like customer, order, shopping card etc.

  1. Define a class in our app’s “model.py” module.

    1. class Products(models.Model): We inherit our class from the model class and our class will have all the capabilities such as storing in a db, reading from a db etc.

  2. Define its attributes.

    1. name = models.CharField(max_length=255)

    2. price = models.FloatField()

    3. stock = models.IntegerField()

    4. image_url = models.CharField(msx_length=2083)


Migrations

We can associate our models with databases.

  1. Download sqlite.

    1. db browser for sqlite

  2. Drag and drop the .sqlite3 file in our project into sqlite.

  3. Django automatically creates tables from models.

    1. In the beginning, we need to do settings so django will recognize our app. Open settings.py file in project and edit INSTALLED_APPS. 

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'products.apps.ProductsConfig'
]


    1. Open terminal and run the command below. It will create a migration and the tables.

python manage.py makemigrations


    1. To generate our table, run the command below:

python manage.py migrate

When we want to add/modify any table in db:

  • Edit models.py file in app (create class etc.)

  • Only execute 3.b and 3.c commands:

    • python manage.py makemigrations

    • python manage.py migrate


Admin

Django comes with an administrative panel by default. We can work with this panel.

  1. Create the first user (super user).

    1. python manage.py createsuperuser

    2. Create username, email and password for the user

  2. After registration with the user, here is our administrative panel. We can manage users and groups.

  1. We can manage our product app from the admin panel. In our product app, open admin.py module. We’ll register the models that we need to manage in the admin section.

    1. from .models import Product

    2. admin.site.register(Product)

  1. We can add a new product (ex. orange) by using Add in our admin panel.


Customizing The Admin

We can customize our product table in the admin area.

  1. In our product app, open admin.py module and create a new class. We inherit it from the ModelAdmin class to use its default methods. Class name is important, “Modelname+Admin” is the convention.

    1. class ProductAdmin(admin.ModelAdmin):

list_display = ('name', 'price', 'stock')

  1. Edit registration configuration.

    1. admin.site.register(Product, ProductAdmin)

Templates

We’ll edit our product page and list the products. We’ll get the products stored in the database and format them using some html template.

  1. Open “views.py” in our product app.

  2. Get all products.

    1. def index(request):

    2.     products = Product.object.all()  # to get all products in table

    3.     # Product.object.filter() to filter ex. cheaper than 2 dollars

    4.     # Product.object.get() to get one product

    5.     # Product.object.save()

  3. Represent products with an html template. Create a directory named as “templates” in the app. Naming is important because Django will look for “templates”.

  4. To create a template for index function, create an “index.html” file in the templates directory. There are 2 special syntaxes in Django:

    1. {% : We use it to dynamically execute logic such as for loops and if statements. It’s called “template tag”.

    2. {{  : We use it to dynamically render values in our html markup.

  5. For the last step, change the return of index function in the views module.

    1. # return HttpResponse('Welcome to Products Page')

    2. return render(request, 'index.html', {'products': products})


Adding Bootstrap

Bootstrap is a potent front-end framework used to create modern websites and web apps. It's open-source and free to use, yet features numerous HTML and CSS templates for UI interface elements such as buttons and forms.

We’ll create a base.html file and make our page more modern. We’ll use the website below to copy some starter templates. 

https://getbootstrap.com/

  1. Create a “base.html” in our app and copy the starter template code.

  2. Edit “index.html” file and extend it from base.html.

    1. {% extends 'base.html' %}

After bootstrap, our page will look more tidy and clean.


Rendering Cards

Now, we’ll make product cards and get rid of the bullet points!

We’ll use Bootstrap’s cards.


Final Touches

For the final, we’ll add a navigation bar and padding to our website. Padding is the space between the web element (text, image, buttons, etc…) and the border of that element.

  1. Move “base.html” to the project. Because it’s in our app now and this means, we can only use it in our app. We’ll have many more apps in a real life application so we need to move the base template to the center of the project. 

  2. Add padding to the index page. Before padding:

  1. Add navbar to the index page from “https://getbootstrap.com/docs/4.5/components/navbar/”.


After adding navigation bar and padding, here it’s the final page we built: