Python Project – Create a Calorie Calculator in Django

Free Python course with 25 real-time projects Start Now!!

In this article, we will develop a Django project – Calorie Calculator. This is a nice intermediate level project to master Django and Python

What is a Calorie Calculator?

”Health is wealth” Obviously, you have heard it a thousand times but as we grow older we often realize it’s true and this app provides an interesting way to get started with the very boring term “dieting” as we already know “FITNESS START WITH WHAT WE EAT”.

Let’s develop an interesting project – Calorie Calculator to record and estimate number of calories we need to consume daily. This app can also provide guidelines for gaining or losing weight.

Calorie Calculator in Python – Django Project

This exciting python project will be developed using a python Django. Django framework provides inbuilt libraries for web development. We can develop any kind of web app using Django.

Project Prerequisites

To implement this app we will use :

  1. Basic concepts of Python
  2. HTML
  3. CSS
  4. Bootstrap
  5. Django framework

To install required libraries, use pip installer from the command line: (Django filters are used and explained later)

pip install django
pip install django-filters

Final product

Below is the final GUI of Calorie Calculator Project

project user home page

Download Project Code

Before proceeding ahead, please download the calorie calculator project source code: Calorie Calculator in Python

Steps to Build a Python Project – Calorie calculator

Now we will make a new project CalorieCalc and an app inside it named ‘Fityfeed’

django-admin startproject CalorieClac
cd  CalorieClac
django-admin startapp Fityfeed

1. Writing Models:

To access databases, we will need the model.

In Fityfeed/, create these models.


from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Customer(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    def __str__(self):
        return str(

class Category(models.Model):
    def __str__(self):

class Fooditem(models.Model):
    name = models.CharField(max_length=200)
    category = models.ManyToManyField(Category)
    carbohydrate = models.DecimalField(max_digits=5,decimal_places=2,default=0)
    fats = models.DecimalField(max_digits=5,decimal_places=2,default=0)
    protein = models.DecimalField(max_digits=5,decimal_places=2,default=0)
    quantity = models.IntegerField(default=1,null=True,blank=True)
    def __str__(self):
        return str(

#for user page-------------------------------------------------------------
class UserFooditem(models.Model):
    customer = models.ManyToManyField(Customer ,blank=True)

Our models will store:

  1. Customers
  2. All available food items
  3. Category of food items we offer
  4. Consumed food items

We are using simple model fields for that purpose. The __str__() method will return the string representation of the object. These are simple Django concepts.

2. Authentication:


from django.http import HttpResponse
from django.shortcuts import redirect

def unauthorized_user(view_func): 
    def wrapper_func(request,*args,**kwargs):
        if request.user.is_authenticated:
            return redirect('home')
            return view_func(request,*args,**kwargs)
    return wrapper_func

def allowed_users(allowed_roles=[]):
    def decorator(view_func): 
        def wrapper_func(request,*args,**kwargs):
            if request.user.groups.exists():
            if group in allowed_roles:
                return view_func(request,*args,**kwargs)
                return HttpResponse("<h1>You are not allowed to access this page</h1>")
        return wrapper_func
    return decorator

def admin_only(view_func):
    def wrapper_func(request,*args,**kwargs):
        if request.user.groups.exists():
        if group=='user':
            return redirect('userPage')
        if group=='admin':
            return view_func(request,*args,**kwargs)
    return wrapper_func

This will take care of all access privileges so that the customer and the admin cannot access each other’s data. Also, it will make sure that the logged-in user can’t go to the login/register page, unauthorized users can’t access any page except login and registration page.

3. Search feature:


import django_filters
from .models import *

class fooditemFilter(django_filters.FilterSet):
    class Meta:
        model = Fooditem
        fields = ['name']

This includes a small code which enables search filter for the user.

4. Creating and updating models:


from django.forms import ModelForm
from .models import *
from django.contrib.auth.forms import UserCreationForm

class fooditemForm(ModelForm):
    class Meta:

class addUserFooditem(ModelForm):
    class Meta:
class createUserForm(UserCreationForm):
    class Meta:

Above mentioned code is required to create, update models which we have created earlier in (for CRUD functionality)

5. To create/update models from django admin site:


from django.contrib import admin
from .models import *

# Now, Register the models here.

class foodAdmin(admin.ModelAdmin):
    class Meta:

It will register all our models to admin site, Now we can easily create/update on following UI:

NOTE: Create a superuser and apply all migrations:

py makemigrations
py migrate
py createsuperuser

It will ask for your username, email, password.

And then boom! You are more than halfway towards reaching your goal.

6. Let’s work with

First, we need to make a new file in our app and include it in ‘CalorieCalc/’ so that it finally contains

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

urlpatterns = [

Now let’s work with Fityfeed/


from django.urls import path,include
from . import views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('user/',views.userPage,name='userPage'), #userPage




It contains a lot more than we’ve discussed right. No worries, we’ll get it as soon as we step further.

7. Let’s finally set our ‘’


from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth.models import User
from .models import *
from .forms import *
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from .decorators import *
from django.contrib.auth.models import Group
from .filters import fooditemFilter
# Create your views here.

def home(request):
    return render(request,'main.html',context)

def fooditem(request):
    return render(request,'fooditem.html',context)

def createfooditem(request):
    form = fooditemForm()
    if request.method == 'POST':
        form = fooditemForm(request.POST)
        if form.is_valid():
            return redirect('/')
    return render(request,'createfooditem.html',context)

def registerPage(request):
    if request.method=='POST':
        if form.is_valid():
            Customer.objects.create(user=user, name=username,email=email)
            messages.success(request,'Account created for '+username)
            return redirect('login')
    return render(request,'register.html',context)

def loginPage(request):
    if request.method=='POST':
        if user is not None:
            return redirect('home')
  ,'username or password is invalid')
    return render(request,'login.html')

def logoutUser(request):
    return redirect('login')

def userPage(request):
    myfilter = fooditemFilter(request.GET,queryset=fooditems)
    for food in myfooditems:
    for items in querysetFood:
        for food_items in items:
    for foods in finalFoodItems:
    return render(request,'user.html',context)

def addFooditem(request):
    if request.method=="POST":
        form =addUserFooditem(request.POST)
        if form.is_valid():
            return redirect('/')
    return render(request,'addUserFooditem.html',context)

Registration Page:

register page

Login Page:

project login page

User Page:

project user home page

Admin Page:

project admin page


7. Let’s do some styling

We need to make a new static folder in the outer project folder. For this, we need to customize our and append the following


STATIC_URL = '/static/'

We need to use this line ‘{% load static %}’ in our templates and now make a new file main.css in our static folder:


.flex-box-row {
    padding : 10px;
    flex-wrap: wrap;
    justify-content: space-around;

    text-shadow: antiquewhite;
    font-family: 'Courier New', Courier, monospace;
    font-weight: 550;
    font-size: xx-large;
    text-align: left;

8. Now the last step, develop templates:

This you can easily get from source code as there are many files so pasting it here would make it bigger.

9. Forget password functionality:

Include this in your



Do not forget to include your email and password here.

10. Output Screens

Below are some random screens of Calorie Calculator Python Project

calorie add food

admin add food item


We have successfully developed the calorie calculator python project in Django and now we can use it every day to keep track of what we eat and how much we should eat.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google | Facebook

20 Responses

  1. Gurpreet says:

    how to run admin page? I mean which command to use?

    • DataFlair Team says:

      Type the following url (remove space) in your browser http :// : 8000/admin change the port number accordingly(if required).

  2. osman says:

    type ‘python runserver’ in command prompt then create username password for your admin login

  3. osman says:

    type;py makemigrations
    py migrate
    py createsuperuser

  4. Gurpreet Singh says:

    could you please give your email?
    I have some doubts….
    I’m not able to access localhost:8000/product page

    • DataFlair Team says:

      Your application port may have different port number (maybe 8080 or any other). You can get it by running ‘py runserver’. You just have to copy this link and append ‘/product’ to the link.

  5. Dhiraj says:

    Can you help me out when I am clicking to view site it is saying change DEBUG=False in I don’t know what to do help me.

    • DataFlair Team says:

      You might not have added the app in your file. So go to the installed app list of the mentioned file and add your app (by appending ‘Fityfeed’) in the list.

  6. Gurpreet Singh says:

    Forget your password functionality isn’t working. Please help!

    • DataFlair Team says:

      You have to provide your own email id and password in the below lines in “EMAIL_HOST_USER=’***’

  7. anita says:

    The view Fityfeed.decorators.wrapper_func didn’t return an HttpResponse object. It returned None instead.

    i am getting above error. please help me

  8. chilljill says:

    I am getting this error as soon as I start migrations

    ModuleNotFoundError: No module named ‘web.urls’

  9. Yad says:

    How do you know how much calories are there in the food ? How will you check that ?


    could i get a report documetation of the project.

  11. Kirtan Patel says:

    Can anyone please guide me, How to create a database for this project?

  12. Onkar Nandkumar Patil says:

    how to run the project in pycharm please explain me step by step

  13. amit kumar mishra says:

    dear sir ValueError at /
    The view Fityfeed.decorators.wrapper_func didn’t return an HttpResponse object. It returned None instead.
    Request Method: GET
    Request URL: http :// : 8000 /
    Django Version: 3.2.2
    Exception Type: ValueError
    Exception Value:
    The view Fityfeed.decorators.wrapper_func didn’t return an HttpResponse object. It returned None instead.
    Exception Location: E:\djangoproject\venv\lib\site-packages\django\core\handlers\, line 309, in check_response
    Python Executable: E:\djangoproject\venv\Scripts\python.exe

  14. goutham says:

    how to run the downloaded code

  15. Ted says:

    Can I turn from web app to mobile app for this calorie tracker ?

  16. Belle says:

    Your HTML templates are not in the source code. Where do I find these??

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.