Blog

  • Create an E-commerce Shop with Django (Part 2)

    Create an E-commerce Shop with Django (Part 2)

    How to create an E-commerce Shop with Django? Part 2.

    Prerequisites

    • Django Latest Version
    • Virtual Environment
    • IDE PyCharm or Visual Studio Code

    Before starting the tutorial don’t forget to activate your Virtual Environment, and the project we created in the previous tutorial.

    1. Create Databases in Models

    Before we start to make an order the first thing to do is create a database that will store order data

    For starters we will make 3 data tables namely:
    – Item will store product data
    – OrderItem will store product data that you want to order
    – Order will store order information

    To create a database in Django framework, we will use models.py file which is in the core directory, open file with your code editor and proceed with this tutorial.

    1. Import
    from django.conf import settings
    from django.db import models
    from django.shortcuts import reverse

    2. Add Item

    CATEGORY = (
        ('S', 'Shirt'),
        ('SP', 'Sport Wear'),
        ('OW', 'Out Wear')
    )
    
    LABEL = (
        ('N', 'NEW'),
        ('BS', 'Best Seller')
    )
    
    class Item(models.Model):
        item_name = models.CharField(max_length=100)
        price = models.FloatField()
        discount_price = models.FloatField(blank=True, null=True)
        category = models.CharField(choices=CATEGORY, max_length=2)
        label = models.CharField(max_length=2)
        description = models.TextField()
    
        def __str__(self):
            return self.item_name
    
        def get_absolute_url(self):
            return reverse("core:product", kwargs={'pk': self.pk})
    
        def get_add_to_cart_url(self):
            return reverse("core:add-to-cart", kwargs={"pk": self.pk})
    
        def get_remove_from_cart_url(self):
            return reverse("core:remove-from-cart", kwargs={"pk": self.pk})

    In the item model you will see there are 3 additional functions, these functions include:

    • get_absolute_url will return url from product
    • get_add_to_cart_url will return url to function add item to cart in views.py file we will make
    • get_remove_from_cart_url will return url to function remove item from cart in views.py file we will make

    3. Add OrderItem

    class OrderItem(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
        ordered = models.BooleanField(default=False)
        item = models.ForeignKey(Item, on_delete=models.CASCADE)
        quantity = models.IntegerField(default=1)
    
        def __str__(self):
            return f'{self.quantity} of {self.item.item_name}'

    OrderItem stores data of the product you want to order and the amount of the product

    4. Add Order

    class Order(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
        items = models.ManyToManyField(OrderItem)
        start_date = models.DateTimeField(auto_now_add=True)
        ordered_date = models.DateTimeField()
        ordered = models.BooleanField(default=False)
    
        def __str__(self):
            return self.user.username

    The Order model will store detailed information of the orders made, but in this part of the tutorial we will not display complete order information, we will add another field in the next part.

    5. Register database to admin

    open core/admin.py file witch code editor and fill with the code below :

    from django.contrib import admin
    from .models import Item, OrderItem, Order 
    admin.site.register(Item)
    admin.site.register(OrderItem)
    admin.site.register(Order)

    That will register your database on the admin page. You can check it on the admin page later

    6 . Migrate model database

    Migrate your model database with the command below :

    $ python manage.py migrate
    $ python manage.py makemigrations

    2. Managing Views

    We have created a database and now it is our turn to manage and manage our views. We will create 2 views that is HomeView and ProductView and 2 function that is add_to_cart() and remove_from_cart(). to continue open core/views.py and continue with the following tutorial

    1. Import
    from django.contrib import messages                       
    from django.shortcuts import render, get_object_or_404, redirect                      
    from django.views.generic import ListView, DetailView                      
    from django.utils import timezone                       
    from .models import (                           
        Item,
        Order,
        OrderItem
    )

    Import all the model classes that we have previously created into views.py

    2. Add HomeView

    In the previous tutorial article, we made a home function to display a view. delete the home function and change it as Class View this :

    class HomeView(ListView):
        model = Item
        template_name = 'core/home.html'

    We use the Item model as a home model and home.html as template view. home.html can be found at templates directory

    3. Add ProductView

    class ProductView(DetailView):
        model = Item
        template_name = 'core/product.html'

    We use the Item model as a home model and product.html as template view. product.html can be found at templates directory

    4. add_to_cart() function

    def add_to_cart(request, pk):
        item = get_object_or_404(Item, pk=pk)
        order_item, created = OrderItem.objects.get_or_create(
            item=item,
            user=request.user,
            ordered=False
        )
        order_qs = Order.objects.filter(user=request.user, ordered=False)
    
        if order_qs.exists():
            order = order_qs[0]
    
            if order.items.filter(item__pk=item.pk).exists():
                order_item.quantity += 1
                order_item.save()
                messages.info(request, "Added quantity Item")
                return redirect("core:product", pk=pk)
            else:
                order.items.add(order_item)
                messages.info(request, "Item added to your cart")
                return redirect("core:product", pk=pk)
        else:
            ordered_date = timezone.now()
            order = Order.objects.create(user=request.user, ordered_date=ordered_date)
            order.items.add(order_item)
            messages.info(request, "Item added to your cart")
            return redirect("core:product", pk=pk)

    This function will add your product to OrderItem database and add detail order to Order database

    5. remove_from_cart() function

    def remove_from_cart(request, pk):
        item = get_object_or_404(Item, pk=pk )
        order_qs = Order.objects.filter(
            user=request.user,
            ordered=False
        )
        if order_qs.exists():
            order = order_qs[0]
            if order.items.filter(item__pk=item.pk).exists():
                order_item = OrderItem.objects.filter(
                    item=item,
                    user=request.user,
                    ordered=False
                )[0]
                order_item.delete()
                messages.info(request, "Item \""+order_item.item.item_name+"\" remove from your cart")
                return redirect("core:product", pk=pk)
            else:
                messages.info(request, "This Item not in your cart")
                return redirect("core:product", pk=pk)
        else:
            #add message doesnt have order
            messages.info(request, "You do not have an Order")
            return redirect("core:product", pk=pk)

    This function will remove all your product from OrderItem database and remove detail order from Order database

    6. Update your templates directory

    In templates directory we make some changes.

    3. Managing Urls

    After the view is finished, then the url will be managed where the view will be displayed in the browser. Open your core/urls.py file and fill with the code below:

    from django.urls import path
    from .views import (
        remove_from_cart,
        add_to_cart,
        ProductView,
        HomeView
    )
    
    
    app_name = 'core'
    
    urlpatterns = [
        path('', HomeView.as_view(), name='home'),
        path('product/<int:pk>', ProductView.as_view(), name="product"),
        path('add-to-cart/<int:pk>', add_to_cart, name='add-to-cart'),
        path('remove-from-cart/<int:pk>', remove_from_cart, name='remove-from-cart'),
    ]

    Import all view classes and functions and add the url for each view.

    4. Demo Aplications

    1. Run your server with the command below :
    $ python manage.py runserver

    2. open http://127.0.0.1:8000/ and choose one product, if you do not have a product you can adding in admin page

    3. Click Add to cart button in product page and you will see the product will add to your OrderItem and Order database

    4. Click remove from cart button to remove your current order. it will delete order item from database Order and OrderItem

    To this end the function to create an order has been implemented

    Proceed to the next part!

    I hope you’ve found the second part of this tutorial helpful. Now you know how to create an E-commerce Shop with Django. In the next session, we’re going to make an Order Summary in our shopping cart.

    Another Django post is about Create a comment model in Django

  • Create a comment model in Django

    Create a comment model in Django

    I decide create a comment model in Django after Create my first open source project – Pyxtract and after learning Django. I wrote code for some Django apps, e.i. my Blog app.

    But how about receiving some feedbacks from your readers and letting them comment in your Django web site or blog?

    (більше…)
  • The Pause Effect and most common words

    The Pause Effect and most common words

    With Pause Effect Python script you can find the topic of any text only parsing 1/30 or 1/50 of all text:

    –https://github.com/skupriienko/Pause-Effect

    Люблю досліджувати. Мабуть, це з дитинства.
    Несподівано виявив, що достатньо 1/30 або 1/50 від усього тексту, щоб зрозуміти основну тему тексту.
    Вирішив назвати цю свою знахідку “The Pause Effect”.

    Якщо спеціальним чином вибрати слова з будь-якого тексту (книга, стаття, туторіал тощо). Ви всі зрозумієте, про що твір, переглянувши на перші 20 найуживаніших слів.

  • Weather Ukraine Kyiv Scraper на Python

    Weather Ukraine Kyiv Scraper на Python

    Написав “Ukraine-Kyiv-Weather-Scraper” після Gmail-reader‘а. Може кому знадобиться. Це Python модуль для автоматичного збирання погоди для м. Києва (Україна) з сайту meteo.gov.ua, результат збирається в файлі csv (кожен раз створюється новий файл із міткою часу).

    Запустіть ukraine_kyiv_weather_scraper.py і ваші результути будуть збережені у папці ‘result_csv’.

  • Мотивація

    Мотивація

    Люблю іноді робити лого та банери.
    На цей раз про мотивацію

  • I analyzed 1000 articles about Python

    I analyzed 1000 articles about Python

    I started studying the Python programming in March 2020.
    Since then, I have reviewed and collected thousands of PDF articles, as well as more than a thousand links to articles.
    This is, so to speak, my learning path and knowledge base.

    (більше…)
  • Create my first open source project – Pyxtract

    Create my first open source project – Pyxtract

    Create my first open source project – Pyxtract:
    – https://github.com/skupriienko/Pyxtract

    Python module for extracting texts from thousands of URL and/or PDF:

    – Download and parsing articles from URLs
    – Extract texts from local PDF files
    – Analyze texts
    – NLP preprocessing
    – Visualization
    – Word clouds
    – Name Entity Recognition

    NER
    Boxplot

  • Fantastic Airtable relational databases

    Fantastic Airtable relational databases

    Four years ago, my life and work became much easier when I mastered the fantastic Airtable relational databases (try it –https://lnkd.in/dpnX4sE). It’s cooler than Google Sheets and intuitively much easier!

    Now I have created an Upwork profile, because I see that there is a need for Airtable experts –https://lnkd.in/dt5qG6e

  • Awesome-Python-Learning v.1.0.1

    Awesome-Python-Learning v.1.0.1

    Extended my Awesome Python Learning dataset (https://airtable.com/shrNtoOfPJVDcO3fG/tblAYr9pYzqpWhYJ0) with new 205 links:

    – Articles about Software Engineering
    – Developer’s Tools
    – MOOC and courses
    – Video

    Here CSV dataset – https://github.com/skupriienko/Awesome-Python-Learning

    P.S. You can try create your own database for everythinghttps://lnkd.in/dpnX4sE

  • Cкільки часу займе записати 1 мільйон рядків у базу даних

    Cкільки часу займе записати 1 мільйон рядків у базу даних

    На співбесіді на Junior Python Developer мене спитали, скільки часу займе записати 1 мільйон рядків у базу даних. Я відразу сказав, що мілісекунди. Ми довго сперечалися, я наводив свої доводи, але після того розмова чомусь швидко завершилася.
    Вирішив перевірити, чи я помилявся. Таки не помилявся, виходить 300 мілісекунд для простого варіанту in-memory. З модулем numpy це буде і того менше – 15 мілісекунд.

    До чого я це кажу? Люблю доводити справу до кінця, навіть якщо інтуїція підказує, що вибрав лише частково правильне рішення.

    UPD. Буду грунтовніше вчити бази даних…

KUPRIENKO