How to Create Card with Button in Django

In this Python tutorial, I will demonstrate to you how to create card with button in Django, where you will see how to make a product card in Django showing the product information such as product image, title, description, and button to view that product.

Additionally, you will learn how to create a product page for a specific product, this product page will appear whenever you click on the view button of any product.

How to Create Card with Button in Django

The first step is to set up the virtual environment for your Django project so follow the below commands.

Create a virtual environment ‘p_card_env’ using the below command in your terminal.

python -m venv p_card_env

Activate this env using the below command.

p_card_env\Scripts\activate

After activating the env, install the Django using the below code.

python -m pip install django

Then create a Django project ‘p_card’ in the current directory using the below command.

django-admin startproject pd_card .

Again create the Django app ‘app_product_card’ using the below command.

django-admin startapp app_product_card
Create Card with Button in Django Project and Env Set Up

Now, open your project in your preferred IDE such as Visual Studio Code, or you can continue with Terminal.

Open the file setting.py of your Django project ‘pd_card’ and the app ‘app_product_card’ within the INSTALLED_APPS section as shown in the below picture.

INSTALLED_APPS = [
    ......,
    ......,
    'app_product_card'
]
Create Card with Button in Django Adding App to Setting File

Run the below command to create the default database and its tables that comes with Django.

python manage.py migrate
Default Tables Create Card with Button in Django

Open the model.py file of the Django app ‘app_product_card’ and create a new model ‘Product’ which will contain information like product name, description, number of orders, product image URL, and product rating of a specific product.

from django.db import models

class Product(models.Model):
    product_name = models.CharField(max_length=200, null= True)
    product_description = models.CharField(max_length=1000, null= True)
    no_product_orders = models.PositiveIntegerField(null= True)
    product_rating = models.PositiveSmallIntegerField(null= True)
    product_image = models.URLField(null=True)

    def __str__(self):
        return self.product_name
Model Product Create Card with Button in Django

Register the model ‘Product’ into the file admin.py of your app.

from django.contrib import admin
from .models import Product
# Register your models here.
admin.site.register(Product)
Create Card with Button in Django Model Registration

Run the below commands in your terminal to migrate the model ‘Product’.

python manage.py makemigrations

python manage.py migrate

After migrating the model, let’s create a view that will fetch all the products from the database and send them to the template.

Create a view ProductView in the views.py file of your Django app ‘app_product_card’.

from django.shortcuts import render
from django.views import View
from .models import Product

class ProductView(View):
    def get(self, request):
        all_product = Product.objects.all()
        context = {'products':all_product}
        return render(request,'product-card.html', context)
Create Card with Button in Django ProductView

The above view gets all the products from the database as objects and sends them to the template’s ‘product-card.html’.

It’s time to set up the URLs, create a new file urls.py in the app ‘app_product_card’, and the following code.

from django.urls import path
from .views import ProductView

urlpatterns = [
   path("",ProductView.as_view(), name= "all-product"),
]
App Level URLs Create Card with Button in Django

Also, set up the project-level URLs, so open the urls.py of your Django project ‘pd_card’ and add the following code.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("app_product_card.urls"))
]
Project Level URLs Create Card with Button in Django

After setting up the URLs, run the Django server by running the following code in your terminal.

python manage.py runserver

Then open your browser and type the URL ‘http://127.0.0.1:8000/admin’ to open the admin panel. If you don’t know how to create an admin user, then read this article Python Django get admin password.

Click on the Product, then click on the Add Product + icon and add the following information as shown in the below picture.

Create Card with Button in Django Adding Product

You can add any product details but remember, in the Product image field provide the URL of the image.

Create the ‘product-card.html’ file within the templates folder of your app, if you haven’t created the templates folder, then create one under your Django app ‘app_product_card’.

And the following code to that file.


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Card</title>
    
</head>

<body>
    <div class="main-container">
        {% for prod in products %}
        <div class="card-container">
            <img src={{prod.product_image}} alt="">
            <div class="card-detail">
                <div class="title">
                    <p>{{prod.product_name}}</p>
                </div>
                <div class="description">
                    <span class="text"> This is the product</span>
                </div>
                <div class="product-rating">
                    <button class="star-rating">&#9734</button>
                    <button class="star-rating">&#9734</button>
                    <button class="star-rating">&#9734</button>
                    <button class="star-rating">&#9734</button>
                    <button class="star-rating">&#9734</button>
                </div>
            </div>
            <a href="{% url 'product' prod.product_name %}"><button class="view-product">View</button></a>
        </div>
        {%endfor%}
    </div>
</body>

</html>
Product Card Html File Create Card with Button in Django

Now open your browser and go to URL ‘http://127.0.0.1:8000’ and you see a page like this if you have followed the steps correctly.

Card with Button in Django Product Page

The above information should appear as a card but it is not like that, because the CSS styling is not applied yet. Let’s configure the project for including static files like CSS, Javascript and etc.

For that, open setting.py file of your Django project ‘pd_card’ and add the following line of code.

STATIC_URL = '/static/'

STATICFILES_DIRS = [
   os.path.join(BASE_DIR, "static"),]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Now create a new folder called ‘static’ at the project with two additional folders ‘css’ and ‘js’ within that folder.

Card with Button in Django Static Files Creation

Then run the below command.

python manage.py collectstatic

After executing the command, if it asks for something type Yes in your terminal. As soon as you hit enter from your terminal, the new folder ‘staticifles’ is created in your project.

Now create two new files style.css and product-style.css within css folder of the static folder and add the following code into the style.css file and leave empty the product-style.css file, we will use this file later.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&family=Roboto:wght@400;700&display=swap');

* {
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html, body {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f0f0f0; 
}

.main-container {
    width: 1000px;
    max-width: 100%;
    height: 800px;
    display: flex;
    flex-wrap: wrap; 
    justify-content: center;
    align-items: center; 
    padding: 10px; 
}

.card-container {
    width: 300px;
    height: 300px; 
    background-color: aliceblue;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 15px;
    border: 1px solid #ddd; 
    margin: 10px; 
    padding: 10px; 
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); 
}

img {
    width: 110px;
    height: 110px;
    border-radius: 60px;
    margin-top: 5px;
}

/* .card-detail {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
} */

.title {
    font-size: 1.2rem;
    font-weight: 500;
    margin-bottom: 5px; 
}

.description .text {
    display: -webkit-box;
    -webkit-line-clamp: 3; 
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

.product-rating {
    margin-top: 8px;
}

.star-rating {
    border: none;
    background-color: unset;
    color: goldenrod;
    font-size: 1.2rem; 
    cursor: pointer; 
}

.view-product {
    padding: 6px 12px; 
    border: none;
    background-color: #007bff; 
    color: #fff; 
    border-radius: 4px;
    cursor: pointer; 
    text-decoration: none; 
    transition: background-color 0.3s ease; 
}

.view-product:hover {
    background-color: #0056b3; 
}
Card with Button in Django CSS Styling

After this, open the HTML file ‘product-card.html’ and add the two lines of code to include the CSS styling.

Card with Button in Django Include CSS Styling
{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}" type="text/css" />

Now again open the URL ‘http://127.0.0.1:8000’ or refresh the page, your page should look like this.

Card with Button in Django

You have successfully created the product card with the button.

Let’s add additional things to this card as when you click on the view button, it will take you to another page where you will see the product name, description, add items button, and buy button with price and product rating.

Now create a view called ‘ProductFilter’ within the view.py file of your Django app and add the following code.

class ProductFilter(View):
    def get(self, request, name):
        print(name)
        product = Product.objects.get(product_name = name)
        context = {'product': product}
        return render(request,'product-page.html',context)
View ProductFilter Card with Button in Django

After creating the product filter, create a new HTML file called ‘product-page.html’ within the folder templates of your Dajngo app ‘app_product_card’ and add the following code in that file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Detail</title>


</head>

<body>
    <div class="product-container">
        <img src={{product.product_image}} alt="">
        <div class="product-detail">
            <div class="product-title">
                <h2>{{product.product_name}}</h2>
            </div>
            <div class="product-description">
                <span> {{product.product_description}}</span>
            </div>
            <div class="add-items">
                <p>Add Items</p>
                <button id="minus">−</button>
                <input type="text" value="1" id="input" />
                <button id="plus">+</button>
            </div>
            <div class="price">
                <p id="product-value">{{product.product_price}}$</p>
                <button class="buy-product">Buy Now</button>
            </div>


            <div class="product-star-rating">

                <button class="p-star-rating">&#9734</button>
                <button class="p-star-rating">&#9734</button>
                <button class="p-star-rating">&#9734</button>
                <button class="p-star-rating">&#9734</button>
                <button class="p-star-rating">&#9734</button>
                <p id="current-rating">0 of 5</p>
            </div>
        </div>
    </div>
</body>
</html>

Setup URLs for this view and template file by opening the urls.py of your Dajango app and add the following line of code.

path("product/<str:name>", ProductFilter.as_view(), name="product")
URLs for ProductFilter Card with Button in Django

Again refresh the browser and open the URL ‘http://127.0.0.1:8000’ and you see the product card, then click on the view button of the product card, the product page look like this.

Create Card with Button in Django Product Page

Again due to styling, the page is not good visually, let’s add some CSS styling to this page by adding the following code in the file product-style.css within css folder of the static folder.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&family=Roboto:wght@400;700&display=swap');

body {
  font-family: 'Poppins', sans-serif;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.product-container {
  background-color: #fff;
  width: 90%;
  max-width: 800px;
  display: flex;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

img {
  width: 100%;
  max-width: 400px;
  height: auto;
  border-radius: 20px 0 0 20px;
}

.product-detail {
  padding: 30px;
  flex: 1;
}

.product-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 10px;
}

.product-description span {
  font-size: 16px;
  color: #555;
  line-height: 1.6;
}

.product-star-rating {
  margin-top: 15px;
}

.product-star-rating p {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-right: 5px;
}

.p-star-rating {
  border: none;
  background-color: unset;
  color: #f1c40f;
  font-size: 2rem;
}

.add-items {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

#input {
  width: 40px;
  text-align: center;
}

#minus,
#plus {
  width: 30px;
  height: 30px;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 18px;
}

#minus:hover,
#plus:hover {
  background-color: #f5f5f5;
}

.price {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

#product-value {
  font-size: 24px;
  font-weight: 600;
  margin-top: 0;
  margin-left: 10px;
}

.buy-product {
  margin-left: 20px;
  margin-bottom: 15px;
  padding: 10px 20px;
  background-color: #3498db;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: background-color 0.3s;
}

.buy-product:hover {
  background-color: #2980b9;
}


@media screen and (max-width: 600px) {
  .product-container {
    flex-direction: column;
  }

  img {
    max-width: 100%;
    border-radius: 20px 20px 0 0;
  }

  .product-detail {
    padding: 20px;
  }

  .product-title {
    font-size: 20px;
  }

  .product-star-rating p {
    font-size: 16px;
  }

  #input {
    width: 30px;
  }

  #minus,
  #plus {
    width: 25px;
    height: 25px;
    font-size: 14px;
  }

  #product-value {
    font-size: 20px;
  }

  .buy-product {
    font-size: 14px;
  }

}

To include the above CSS styling to the page ‘product-page.html’, add the following line of code to that HTML page.

{% load static %}

<link rel="stylesheet" href="{% static 'css/product-style.css' %}" type="text/css" />
Create Card with Button in Django Product Page Styling

Run the below command.

python manage.py collectstatic

Again open the product card page and click on any product, you see the product page like this.

Product Page Create Card with Button in Django

If you see a page like the above then you have successfully created the product page for a specific product.

Let’s add some functionality to add the number of items when you click on the plus and minus buttons and also implement the functionality for rating of the product, when click on the rating star, it will show the number of ratings given to this product.

Create a new file ‘script.js’ with the js folder of the static directory and add the following code.

const plusButton = document.getElementById("plus");
const minusButton = document.getElementById("minus");

const inputData = document.getElementById("input");
plusButton.addEventListener('click',()=>{
    inputValue = parseInt(inputData.value);
    inputValue = inputValue + 1;
    inputData.value = inputValue;
})


minusButton.addEventListener('click',()=>{
    inputValue = parseInt(inputData.value);
    if(inputValue > 1 ){
        inputValue = inputValue - 1;
        inputData.value = inputValue;
    }
})



const stars=document.querySelectorAll('.p-star-rating');
const current_rating=document.getElementById("current-rating");

stars.forEach((star,index)=>{
  star.addEventListener('click',()=>{

    let current_star=index+1;
    current_rating.innerText=`${current_star} of 5`;

    stars.forEach((star,i)=>{
        if(current_star>=i+1){
          star.innerHTML='&#9733;';
        }else{
          star.innerHTML='&#9734;';
        }
    });

  });
});

Include the above script.js file into the template file ‘product-page.html’ by adding the following line of code.

<script src="{% static '/js/script.js' %}"></script>
Product Page Javascript Create Card with Button in Django

Again run the below command in your terminal.

python manage.py collectstatic

Again refresh the product page and click on the plus or minus button, the number of items being increased and decreased, and also click on the star rating button.

Create Product Card with Button in Django

Conclusion

In this Python tutorial, you learned how to create a product card with a button and also learned how to create a product page for a specific product. Especially you learned how to fetch data from the database and create this product card or page dynamically using Django.

You may like to read: