> ## Content Index
> Fetch the complete content index at: https://evil-penguin.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Django Basics
- URL: https://evil-penguin.com/django-basics/
- Published: 2023-04-22T17:55:20.000Z
- Updated: 2026-11-16T23:03:40.000Z
- Description: How to Develop a Basic Django application
- Author: evilpenguin
- Tags: Python, JavaScript

## Intro

We will create a Demo Project with Django which uses a default base Template and integrate it with D3  
  
📁 Create project foldermkdir 42-portfolio-demo   
cd 42-portfolio-demo  
🌏 Create and load a virtual environment

> This will create a Pipfile as well

sudo pipenv shellpipenv install djangodjango-admin startproject portfolio\_suite  
cd portfolio\_suitepython manage.py startapp portfolio\_app  
python manage.py migrate  
python manage.py runserver 3001  
🏛️ Now let's define the Models, this is the Structure for our DataBase

> *portfolio\_app/models.py*

from django.db import models  
  
class User(models.Model):  
 intr\_username = models.CharField(max\_length=30)  
 intra\_id = models.IntegerField(unique=True, db\_index=True)  
 first\_name = models.CharField(max\_length=50)  
 last\_name = models.CharField(max\_length=50)  
 email = models.CharField(max\_length=150)  
 bio = models.TextField(max\_length=800)  
 updated\_at = models.DateTimeField(auto\_created=True, auto\_now=True)  
  
 def \_str\_(self):  
 return "@" + self.intr\_username  
This will create a migration file where you can see all changes that will be done to the database.python manage.py makemigrations portfolio\_app

> ...  
> ...

mistake on email field, should be EmailFieldrm portfolio\_app/migrations/0001\_initial.py  
The migrate command will make the database take effect upon the migrations on the migrations folder.

> Change model to EmailField and make the migration

python manage.py makemigrations portfolio\_app  
python manage.py migrate portfolio\_app  
Add your User to the Admin module

> *portfolio\_app/admin.py*from django.contrib import admin  
> from .models import User  
>  
> class UserAdmin(admin.ModelAdmin):  
> fields = \['intra\_id', 'intra\_username', 'first\_name', 'last\_name', 'email'\]  
> list\_display = ('intra\_username', 'first\_name', 'last\_name', 'email', 'updated\_at')  
>  
>  
> admin.site.register(User, UserAdmin)  

🔑 Create a SuperUser to access the Adminpython manage.py createsuperuser  
Username: test  
Password: test1234  
Or whatever you want (never put test1234 as a password on production ofcs...)python manage.py runserver 3001

![](https://evil-penguin.com/content/images/2026/11/Screenshot_2023-04-22_at_11.35.36.png)

> *portfolio\_app/views.py*

from django.shortcuts import render  
from django.http import HttpResponse  
  
def usersIndex(request):  
 return HttpResponse("Hello, world. You're at the users index.")

> *portfolio\_suite/urls.py*

from django.contrib import admin  
from django.urls import path  
from portfolio\_app import views  
  
urlpatterns = \[  
 path('admin/', admin.site.urls),  
 path('users/', views.usersIndex, name="usersIndex")  
\]

![](https://evil-penguin.com/content/images/2026/11/Screenshot_2023-04-22_at_12.04.28.png)

🦪 To explore a minimalistic inner structured shell for your application you can run:

> python manage.py shell

**from** **portfolio\_app.models** **import** User  
User.objects.all()  
  
User.objects.get(id=1)  
User.objects.get(intra\_username="arosado")  
🔗 Setting a urls module for the portfolio:

> *portfolio\_app/urls.py*

from django.urls import path  
  
from . import views  
  
urlpatterns = \[  
 path("users/", views.usersIndex, name="usersIndex"),  
\]

> *portfolio\_suite/urls.py*

from django.contrib import admin  
from django.urls import path, include  
  
urlpatterns = \[  
 path('admin/', admin.site.urls),  
 path("", include("portfolio\_app.urls")),  
\]  
Try again the routes make sure it works!  
  
Add one more route:

> *portfolio\_app/urls.py*

...  
path("users/<str:intra\_username>", views.userShow, name="userShow"),That is a dynamic route, and you can access the value which will be a string input by the user on the url. Based on that value we will return the view with the username if it exists.  
  
Add the method to the views:

> *portfolio\_app/views.py*

from django.shortcuts import render, get\_object\_or\_404  
from .models import User  
  
...  
  
def userShow(request, intra\_username):  
 return HttpResponse("Hello, world. You're at the user \[%s\] page." % intra\_username)  
As you can see, you can access the parameter on the views.  
  
run the server and visit: **users/your\_param**

## Templates

In order to recycle code we can build templates and develop contexts so we can contain the application under the same template.  
♻️ This way we avoid having a bunch of html files with headers and repetitive stuff.  
  
mkdir -p mkdir portfolio\_app/templates/users  
touch portfolio\_app/templates/users/show.html

> *portfolio\_app/views.py*

from django.shortcuts import render, get\_object\_or\_404  
from django.http import HttpResponse  
from .models import User  
  
...  
  
def userShow(request, intra\_username):  
 user = get\_object\_or\_404(User, intra\_username=intra\_username)  
 return render(request, "users/show.html", {"user": user})Beware, the parameters must be passed through a dictionary 📚  
  
  
> *portfolio\_app/templates/users/show.html*

{% load static %}  
<link rel="stylesheet" href="{% static 'users/style.css' %}">  
  
USER: {{ user.first\_name }}  
Now let's create that static cascade style sheetmkdir -p portfolio\_app/static/users  
touch portfolio\_app/static/users/style.css  
touch portfolio\_app/static/base.css  
Now we need a base html template:touch portfolio\_app/templates/base.html

> base.html

  
<html lang="en">  
<head>  
 {% load static %}  
 <link rel="stylesheet" href="{% static 'base.css' %}">  
 <title>{% block title %}42Portfolio{% endblock %}</title>  
 {% block custom\_style\_sheets %}{% endblock %}  
</head>  
  
<body>  
 <nav><h1>42 Portfolio</h1></nav>  
  
 <div id="content">  
 {% block content %}{% endblock %}  
 </div>  
  
 <footer>all rights reserved by 42 Lisboa</footer>  
</body>  
</html>

> *portfolio\_app/static/base.css*

@keyframes gradient {  
 0% {  
 background-position: 0% 50%;  
 }  
 50% {  
 background-position: 100% 50%;  
 }  
 100% {  
 background-position: 0% 50%;  
 }  
}  
  
body {  
 width: 100vw;  
 min-height: 100vh;  
 margin: 0;  
 background: linear-gradient(-45deg, rgba(42, 42, 42, 0.1), rgba(42, 42, 42, 0.4), rgba(42, 42, 42, 0.3), rgba(42, 42, 42, 0.2));  
 background-size: 200% 200%;  
 animation: gradient 10s ease infinite;  
 font-family: 'Nova Mono', monospace;  
}

> *portfolio\_app/static/users/style.css*

b {  
 color: pink;  
}

> *portfolio/templates/users/show.html*

{% extends "base.html" %}  
  
{% block title %}{{ user.intra\_username }}{% endblock %}  
  
{% block custom\_style\_sheets %}  
{% load static %}  
<link rel="stylesheet" href="{% static 'users/style.css' %}">  
{% endblock %}  
  
{% block content %}  
<h4>USER: <b>{{ user.first\_name }}</b></h4>  
{% endblock %}

![](https://evil-penguin.com/content/images/2026/11/Screenshot_2023-04-22_at_13.22.27.png)

## Adding custom JavaScript

Add a block to your template's header:  
(I also added the link to d3.min.js because I want to use it all over this template)  
  
> *portfolio\_app/templates/base.html*

<script src="https://d3js.org/d3.v7.min.js"></script>  
{% block custom\_javascripts %}{% endblock %}  
Now let's create a js file under the static foldertouch portfolio\_app/static/users/portfolioCard.js  
Load the custom js to the view where you want to use it:

> portfolio\_app/templates/users/show.html

{% block custom\_javascripts %}  
<script type="text/javascript" src="{% static 'users/portfolioCard.js' %}"></script>  
{% endblock %}  
Great it works! But how can I for example, use the User model with JS!?  
  
Well we can serialize the Object and the convert to JSON and deserialize in the JS ;)  
  
So let's try to do that:  
  
> *portfolio\_app/views.py*

from django.shortcuts import render, get\_object\_or\_404  
from django.http import HttpResponse  
from .models import User  
from django.core.serializers import serialize  
**from django.core.serializers.json import DjangoJSONEncoder**  
  
def usersIndex(request):  
 return HttpResponse("Hello, world. You're at the users index.")  
  
def userShow(request, intra\_username):  
 user = get\_object\_or\_404(User, intra\_username=intra\_username)  
**serialized\_user = serialize('json', \[user\], cls=DjangoJSONEncoder)**  
 return render(request, "users/show.html", {"user": user, **"serialized\_user": serialized\_user\[1:-1\]**})

> *portfolio\_app/templates/users/show.html*

...  
  
{% block custom\_javascripts %}  
<script type="text/javascript" src="{% static 'users/portfolioCard.js' %}"  
 defer  
**data-user="{{ serialized\_user }}**">  
</script>  
{% endblock %}  
  
...  
***defer:*** to load after all the document was loaded completely and we pass the **serialized** user through a **data-set**  
  
Now we can access the data-set and see the object:  
  
> *portfolio\_app/static/users/portfolioCarsd.js*

const data = document.currentScript.dataset;  
const user = JSON.parse(data.user);  
  
console.log(user)

![](https://evil-penguin.com/content/images/2026/11/Screenshot_2023-04-22_at_13.47.32.png)

Let's add a nice svg! :)  
  
> *portfolio\_app/static/users/portfolioCarsd.js*

const svgHeight = 300, svgWidth = 600;  
const data = document.currentScript.dataset;  
const user = JSON.parse(data.user);  
  
// console.log(user)  
  
window.addEventListener("load", () => {  
 d3.select( "#content" ).append( "svg" )  
  
 d3.selectAll( "svg" )  
 .attr( "width", svgWidth )  
 .attr( "height", svgHeight );  
});  
Add some style to the base.css for the #content id  
  
> *portfolio\_app/static/base.css*

body {  
 ...  
 text-align: center;  
}  
  
#content {  
 display: flex;  
 align-items: center;  
 justify-items: center;  
 flex-flow: column;  
 gap: 1.5rem;  
 margin: 1rem auto;  
 padding-bottom: 1rem;  
 max-width: 800px;  
 background-image: url("https://i.pinimg.com/originals/70/72/c0/7072c003a01ab656c982542e9c38c475.jpg");  
 background-size: cover;  
 background-position: center;  
}

> portfolio\_app/static/users/style.css

h4 {  
 background-color: rgba(255, 255, 255, 0.8);  
 padding: 0.25rem;  
 border-radius: 0.25rem;  
}  
  
b {  
 color: pink;  
}  
  
svg {  
 margin: auto;  
 display: inline-block;  
 background-color: rgba(42, 42, 142, 0.9);  
}  
Now have fun, you can do this to see some drag interactions on your svg, just to test the d3 library and how powerful it can be!!!  
  
> portfolio\_app/static/users/style.css

const svgHeight = 300, svgWidth = 600;  
const data = document.currentScript.dataset;  
const user = JSON.parse(data.user);  
  
// console.log(user)  
  
const drawCircles2 = (svg, circles) => {  
 svg.selectAll( "circle" )  
 .data( circles ).enter().append( "circle" )  
 .attr( "r", d => d\["r"\] )  
 .attr( "cx", d => d\["cx"\] )  
 .attr( "cy", d => d\["cy"\] )  
 .attr( "fill", d => d\["color"\] );  
}  
  
window.addEventListener("load", () => {  
 const svg = d3.select( "#content" ).append( "svg" )  
 .attr( "id", "drag-drop")  
  
 d3.selectAll( "svg" )  
 .attr( "width", svgWidth )  
 .attr( "height", svgHeight );  
  
 let circles = \[  
 {r: 20, color: "red", cx: 50, cy: 100},  
 {r: 20, color: "green", cx: 250, cy: 150},  
 {r: 20, color: "blue", cx: 350, cy: 100}  
 \];  
 drawCircles2( svg, circles );  
  
 let color = undefined, widget = undefined;  
  
 svg.selectAll( "circle" )  
 .call( d3.drag()  
 .on( "start", function () {  
 color = d3.select( this ).attr( "fill" );  
 widget = d3.select( this ).attr( "fill", "lime" );  
 } )  
 .on( "drag", function () {  
 let pt = d3.pointer( event, this );  
 widget.attr( "cx", pt\[0\] ).attr( "cy", pt\[1\] )  
 } )  
 .on( "end", function () {  
 widget.attr( "fill", color );  
 widget = undefined;  
 color = undefined;  
 } )  
 );  
});

![](https://evil-penguin.com/content/images/2026/11/ezgif.com-video-to-gif_3_.gif)

Now we just need more data to actually create a nice visualization instead of this circles... You can use React for example and develop a REST API in Django!  
  
Repo: [https://github.com/pulgamecanica/42Portfolio-Demo/](https://github.com/pulgamecanica/42Portfolio-Demo/tree/6c4b55999d17cc08114b71013eb410661ad90e82?ref=evil-penguin.com)