- created a vitual environment
- create a
.gitignorefile - activate the environment:
- windows:
.\env\Scripts\activate - linux:
source env/bin/activate
- windows:
- install django:
pip install Django - add the
envroute(relative route) inside the.gitignore - create a django-project:
django-admin startproject projectFarm cd(change directory- helps you navigate inside a directory) into theprojectFarm- confirm your directory using either
dirorls, you should spotmanage.pyfile - run first django project:
python manage.py runserver
-
python manage.py startapp firstApp -
register the application in the main project:
- navigate to project level settings.py:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'firstApp' ]
- navigate to project level settings.py:
-
add it to the path in the
projectlevelurls.py:from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('firstApp/',include('firstApp.urls')) ] -
create a
urls.pyinside thefirstAppdirectory:from django.urls import path # helps us import the method path for our endpoints from . import views # import veiws from the current root directory # endpoints + target view functions urlpatterns = [ path('produce', views.produceSector) ] -
run it once more
-
create model class for
produce:class Produce(models.Model): # name of the table name = models.CharField(max_length=200) # strings with a max length in character of 200 description = models.CharField(max_length=255) # strings with a max length in character of 255 price = models.FloatField() # float numbers eg 20.25
- create superuser
python manage.py createsuperuser:
- run the app:
python manage.py runserver - navigate to
/adminendpoint:
-
navigate to the
admin.py(in app directory/folder) and register the modelsfrom django.contrib import admin from . import models # models # Register your models here. admin.site.register(models.Produce) -
refresh your admin panel (assuming you are still runnning the project):

-
navigate to the projct root folder i.e inside
projectFarm -
create a subfolder inside it and call it
templates -
navigate to
settings.py(found inside the projectfolder) and add this configurationTEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
create a
main.htmlfile inside it:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous"> <script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script> </head> <body> <div class="container my-5"> <div class="display-6"> Welcome Home </div> </div> </body> </html> -
updated the view funtion related to it:
# Create your views here. def produceSector(request): return render(request, 'main.html') -
we will now inherit templates using:
{% extends 'main.html' %} -
we will also create a container area for different pages:
{% block content %} {% endblock %} -
now update your
main.htmlas this:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous"> <script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script> </head> <body> {% include 'nav.html' %} {% block content %} {% endblock %} </body> </html> -
create
home.htmlinside the templates directory:{% extends 'main.html' %} {% block content %} <div class="container my-5"> <div class="display-6"> Welcome Home </div> </div> {% endblock %} -
decouple the app related template:
-
update your
views.pyfile:# Create your views here. def produceSector(request): return render(request, 'firstApp/home.html')
- adding the navbar
- on the hrefs, place the routes as such:
{% url '{nameOfRoute}' %}
- create a model for the data:
class Fruit(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=255) # strings with a max length in character of 255 price = models.FloatField() # float numbers eg 20.25 created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) class Meta: ordering = [-created_at,-updated_at] def __str__(self): return self.name - add(register) the model to the admin panel, navigate to the app level
admin.py:from django.contrib import admin from . import models # models # Register your models here. admin.site.register(models.Produce) admin.site.register(models.Fruit)
- Preparing the functions to enable CRUD operarions
def createFruit(request):
return render(request)
def readAllFruits(request):
return render(request)
def readOneFruit(request):
return render(request)
def updateFruit(request):
return render(request)
def deletFruit(request):
return render(request)
from django.urls import path # helps us import the method path for our endpoints from . import views # import veiws from the current root directory
```
path('readAll', views.marketSector, name ='readAll'),
path('readOne/<str:pk>', views.readOneFruit, name ='readOne'),
```
-
Create a Form(ModelForm):
- create a file under the app folder called
forms.py - create model form:
from django.forms import ModelForm from .models import Fruit class FruitForm(ModelForm): class Meta: model = Fruit fields = '__all__' # or target specific columns eg ['name', 'description', 'price]
- create a file under the app folder called
-
navigate to
urls.pyand import theFruitForm,from .forms import FruitForm -
update the view function to create the new record:
def createFruit(request):
form = FruitForm()
context = {"form":form}
if request.method == "POST":
form = FruitForm(request.POST)
if form.is_valid():
form.save()
return redirect("market")
return render(request, "firstApp/form.html", context )
- create
form.html:
{% extends 'main.html' %}
{% block content %}
<div class="container my-5">
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit">
</form>
</div>
{% endblock %}
-
key important bits:
Fruit.objects.all(): fetched all the data under the Fruits tablesFruit.objects.get(id=pk): fetched the fruit data where id was pk(primary key)
-
read all data from DB, update our
views.pyfile:def readAllFruits(request): fruits = Fruit.objects.all() # ORM helps us not write sQL syntax here => transalates to SELECT * FROM fruits; context = {"fruits":fruits} return render(request,"firstApp/market.html", context) def readOneFruit(request,pk): fruit = Fruit.objects.get(id = pk) context ={"fruit":fruit} return render(request,"firstApp/fruit_details.html", context)
```
{% extends 'main.html' %}
{% block content %}
<div class="container my-5">
<div class="display-3"> Welcome to the Market SPACE!! </div>
<hr>
<!-- <div class="fs-6"> {{ fruits }} </div> -->
{% for fruit in fruits %}
<div class="display-5">{{fruit.name}}</div>
<p class="lead">{{fruit.description}}</p>
<div class="badge bg-dark">ksh. {{fruit.price}}</div>
<hr>
{% endfor %}
</div>
{% endblock %}
```




