Building an EC App with Django | Introducing Django (Part 2)

 2021-09-16

Building an EC App with Django | Introducing Django (Part 2)

Continuing from our previous article on building e-commerce applications with Python Django, we'll move on to Part 2 where we'll add features to make your application more complete. In this article, Hachinet will explain in detail the three main functions.

 

1. Shopping cart function


1.1. Product list paging

Django often provides actions related to paging. The page is displayed through various URLs. Everything is inherited from the Class Paginator.

You can build your own paging feature through Django's detailed instructions here.

Last time, we got all the products and displayed the store page using the URL of "http://127.0.0.1:8000/store/". You need to make the following changes in the store function (GreatKart / store / views.py):

  • Get the page argument delivered by the client by URL.

"Http://127.0.0.1:8000/store/?page=2" (this page argument can be customized):

If "page = page or 1 # URL is http://127.0.0.1:8000/store", the default is page number 1.

  • Create a Paginator object with two arguments. The first argument is a list of all the elements you want to page. The second argument is the number of pages, with n.

paginator = Paginator (products, 3) # n = 3

Get all the goods and count them.

The template does the same thing as Django tells you. You can search for code templates here.

 

1.2 Search for products

Add the URL path ('search /', Views.search, name ='search') to Store / urls.py. Add a Search function to Store / views.py so that it looks like this:

  • Search for the argument q in Request and deliver it to the Server.
  • Filters products by argument q, based on the queries that Django supports.

Product.objects.order_by ('-created_date'). filter (Q (product_name__icontains = q) | Q (description__icontains = q))

See here for specific code for the search function. See here for Form search templates.

 

1.3 Add / Remove Items to Shopping Cart

Before we talk about adding or removing items from your shopping cart, we'll use another model Variation to describe a variety of items. Add the code to the app store's model.py.

Class Variation Manager (models.Manager):

def colors (self): # Returns all records with type color

Return super (VariationManager, self) .filter (variation_category ='color', is_active = True)

Def sizes (self):

        # Returns all records with type size

        Return super (VariationManager, self) .filter (variation_category ='size', is_active = True)

variation_category_choice = (

    ('color', 'color'),

    ('size', 'size'),

)

class Variation(models.Model):

    product = models.ForeignKey (Product, on_delete = models.CASCADE) #Foreign key is product_id

    Variation_category = models.CharField (max_length = 100, choices = variation_category_choice) Contains two fixed types: #color and size.

    variation_value = models.CharField(max_length=100)

    is_active = models.BooleanField(default=True)

    created_date = models.DateTimeField(auto_now_add=True)

    objects = VariationManager()

    def __str__(self):

        return self.variation_value

Don't forget to add the admin.py file so that Admin can manage the table.

Hachinet has listed the URLs here about building URLs.

There are the following functions for view functions that are applied to add/delete products.

  • rt_id: If this is your first visit to your local computer, create a shopping cart ID in session_storage. If the ID already exists in session_storage, just get it.
  • add_cart: _cart_id Use a function to make sure you save one Cart on your local computer. If the Cart does not have a CartItem, the function will add a new CartItem. Or add one quantity unit to the saved CartItem.
  • remove_cart: Decrease 1 quantity unit to CartItem.
  • remove_cart_item: Removes 1 CartItem from Cart.

 

1.4 Shopping cart Context Processor

After having enough operations to add/remove products, update the number of products to the cart icon in the upper right corner.

This display is displayed on all pages of the application. You can't get the data and display them with all the functions in views.py. Django only gets the context processor support once and it helps to display it in all URLs.

First, go to the settings.py file, which is the TEMPLATES key OPTIONS, and put it in an array variable.

Add'carts.context_processors.counter',.

Then create a new file context_processors.py in the app cart, add the counter function here and always go back to the dictionary.

 

2. User authentication function


2.1 Registration

Create a new URL in the app account file urls.py. Then declare a function in the view you want to apply.

Django often supports creating forms. Create a new file forms.py and create a class that inherits from ModelForm. Create the form registration targets with the view's register function and display them in the template. You can see the code to create on the form here.

Place the POST method in the action register in the template's Form tag. That is, the form's register function checks if the submitted request has a GET or POST method.

For POST, create a new user through the create_user function, which is models.py in your app account.

Go back to settings.py and someday add a line code to make it different than Django's customization.

Add setTimeout in greatkart/static/js /script.js so that the message closes automatically after a few seconds.

After creating the user, add the message messages.success (request = request, message = "Registration successful!") In the register function.

 

2.2 Login

First, create one URL and one login function in the views.py file of your app account.

You'll fill in two fields, login and email, so you don't have to create a form target.

Add messages for successful and unsuccessful logins.

The template is at the same level as the login template. We left the is_active field False after login, so it can be changed to True for that account on the Admin page and log in.

 

2.3 Logout

Customize fewer functions with logout in views.py.

from django.contrib.auth.decorators import login_required

@login_required (login_url = "login") # Django supports you to make sure you need to log in before you can log out.

def logout(request):

    auth.logout(request)

messages.success(request=request, message="You are logged out!")

    return redirect('login')

 

2.4 Authenticate email after registration

Authenticate the email source to deliver to the email registration by adding a variable to the settings.py file. Don't forget to open access to third parties to your google account here. If you don't use it, you can turn it off.

# Don't forget to go to the file.

EMAIL_USE_TLS = True

EMAIL_HOST ='smtp.gmail.com'

EMAIL_HOST_USER ='youremail@gmail.com'

EMAIL_HOST_PASSWORD ='yourpassword'

EMAIL_PORT = 587

After registering, Hachinet redirected to the registration page, and notified me to wait for the registration email to take effect. Send the link in an email with two arguments.

  • Encrypt user's id with Django's class HTTP.
  • Tokens are created from the six libraries and stored in a server session.

The user receives the email and clicks on the link. The system then takes the first argument to decorate and gets the user id. Get the second argument token to see if the session exists on the server. If both conditions are met, update the is_active field and return to the login page to continue. Otherwise, it will report an error.

 

2.5 Add dashboard to the account page

Add a root/accounts/dashboard link to manage your account. See the template on Github.

 

2.6 Forget password and reset password

Use the ability to deliver Django email credentials to complete the password reset feature.

Create a forgotPassword link for users to enter their email address to authenticate which user's account matches their email address. If you want to save it, we will send you an email with the same link as the registration function.

reset_password_validate / <uidb64> / <token>

Next, create a single URL called reset_password_validate. If the path is valid, it returns a path named reset_password so that the user can change the password. You need to attach the uid to the request to verify that the session is the correct user.

Check the request uid with the reset_password link and use user.set_password (password) to update the patchwork to the user.

 

3. Paypal payment function


3.1 User checkout page and required tables

First, we designed a new app called Orders that has three tables:

  • Order tables and records are created each time a user places an order. This table contains foreign keys to your account and payments.
  • In the OrderProduct table, each record corresponds to one row in the cart when payment is complete. This table contains foreign keys for orders and payments.
  • Payment tables and records are created each time a user completes a payment. The payment_id field is used to store the transaction ID. This table contains only foreign keys to your account.

Then create a form for the user with a checkout page and information related to order delivery.

Includes a simple staircase to create a single URL in app Cart, create a function checkout, and create a template.

 

3.2. Payment gateway integration and ordering

Create one Paypal account. Then go to the page and register.

Go to the tab "https://developer.paypal.com/" and "https://developer.paypal.com/developer/accounts/" to create a sandbox account.

Create personal (buyer) and business (seller) accounts through the information as follows:

  • Personal email is my.app.personal@gmail.com
  • Business email is my.app.business@gmail.com

Both my accounts are $ 9,999,999 and the payment card type is VISA. After creating two sandbox accounts, you can log in to "https://sandbox.paypal.com/" to check the available amount.

Go to this page "https://developer.paypal.com/developer/applications/"

I created a new app called My Great kart. The sandbox account you selected is the sandbox business account above. Leave the app type as it is. After creating, copy the Client ID of the newly created app.

"Https://developer.paypal.com/demo/checkout/#/pattern/client"

Next, I created a PayPal button for the user (detailed instructions can be found on the Paypal home page "https://developer.paypal.com/docs/checkout/integrate/"). You can see the demo here. "Https://developer.paypal.com/demo/checkout/#/pattern/client"

Add the button and script code to the orders / payments.html file.

<div id="paypal-button-container"></div>

<script>

        var amount = "{{ grand_total }}";

        // Render the PayPal button into #paypal-button-container

        paypal.Buttons({

            // Set up the transaction

            createOrder: function(data, actions) {

                return actions.order.create({

                    purchase_units: [{

                        amount: {

                            value: amount,

                        }

                    }]

                });

            },

            // Finalize the transaction

            onApprove: function(data, actions) {

                return actions.order.capture().then(function(details) {

                    // Show a success message to the buyer

                    alert('Transaction completed by ' + details.payer.name.given_name + '!');

                });

            },

            style: {

                color:  'blue',

                shape:  'pill',

                label:  'pay',

                height: 40

            }

        }).render('#paypal-button-container');

    </script>

3.3. Update database after payment

In Paypal's approve event, add ajax to update the database with the data sent as follows:

  • csrfmiddlewaretoken: Similar to csrf_token in HTML form
  • orderID: ID of the order record
  • transID: ID of the transaction just performed
  • payment_method = "PayPal"
  • status: Transaction status just created

Check if the request sent in the views.py part is of ajax and POST type, then do the following:

  • Create a new Payment record
  • Update record
  • Each CartItem record creates a corresponding OrderProduct record. Also, delete the CartItem.
  • Deliver an email to notify the user

 

4. Summary


So Hachinet has briefly introduced what Django is, how to do it, and what Django does. For large platforms and many users, this is the ideal framework for working efficiency.

Many companies around the world, including Instagram, Spotify, Dropbox, NASA, Pinterest, and Reddit, are seizing the opportunity to use Django applications. Large websites designed with the support of this framework provide very strong performance. Django is free, simple, and one of the best Python web frameworks on the market.

 

If you are considering offshore development, please feel free to contact us.

Here is our contact information.

Account Manager: Quan (Japanese/English available)

Phone number: (+84) 2462 900 388

Email: contact@hachinet.com

Please feel free to contact us for consultation/application by phone.

Click here for more information ▶