CodeCraze🚀 - create your own blog in Django | Part 0 | Project Setup
Tags: python, django, beginners, website
Published: 2023-11-09 17:24:06


Hola Amigos!!

In this Article, we create our own blog called **CodeCraze** using [Django](https://www.djangoproject.com/), a popular web framework written in python. Django is designed to help developers to rapidly build their web applications from concept to completion in an efficient way. Its a **batteries included** framework which provides out of the box functionalities such as *ORM*, *API Integration*, *authentication*, *form handling* & many more... 

Django follows MVC (Model View Controller) Architecture which focuses on 

✅ **reusability** <br>✅ **scalability** & <br>✅ **maintainability** 

The most exciting part is, its completely open-source! 🥳

During this journey, we will build our blog step by step which covers important topics such as CRUD, authentication, profile creation, API Integration, comment section and others, to familiarize ourselves with the concepts.

For Part 0, we focus on project setup before actual coding, so without getting further delay let's get started...

---

### Ingredients:

📌 python 3
📌 git
📌 virtualenv 
📌 django

---
## Creating virtual env

The importance of building our project in virtual environment is to isolate & manage python packages for different projects without interfering globally installed packages at OS level. We will be creating our blog on linux (ubuntu distro), I highly recommend you to work on linux or linux image installed in WSL. 


- Before diving, lets create an alias for python3 command to eliminate typing whole word. In my case I'm using fish shell,

for fish shell,
```bash
echo "alias py=python3" >> $HOME/.config/fish/config.fish
```

for bash,
```bash
echo "alias py=python3" >> ~/.bashrc
```

-  Firstly we install our `virtualenv` package via pip 
```python
py -m pip install --user virtualenv
```

- Once the respective package has been installed, we create a virtual environment by specifying the directory of your choice and install `django`
```bash
mkdir -p $HOME/tutorial/pyenv
```
```python

py -m venv $HOME/tutorial/pyenv
```

![Project Directory Creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvhcb3xq9icf9bmot8uc.png)

- when our setup got created, activate the virtual env, run the below command

for fish
```bash
cd $HOME/tutorial/pyenv && source bin/activate.fish
```

for bash,
```bash
cd $HOME/tutorial/pyenv && source bin/activate
```

- To verify whether you have correctly created virtual env is by seeing `pyenv` in your prompt

![virtualenv setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6rkppbl8rejbhfq0sb2j.png)

- Now we install `django` package
```python
pip install django
```

- Check the version of the installed django
```python
py -m django --version
```
![Django Installation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/romtzas2rxuhwpfmkzva.png)

---
## Django Project setup

- Now lets create a django project under `$HOME/tutorial/pyenv/` path
```python
django-admin startproject codecraze .
```

- Now let's create a `requirement.txt` file to store our dependencies as a best practice, so that the correct packages can be installed on other machine for collaborating with others. Also make sure to update *requirements.txt* whenever you install any new packages for your project.
```bash
cd codecraze && pip freeze > requirement.txt
```
![creating requirements.txt file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s28uyrzvtmaolaw0qkp.png)

- Initialize the `pyenv` directoy as git repository
![Initializing git repo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sy43nt3zrhsuhs7c4aby.png)

- Lets create `.gitignore` file, to ignore library files while doing our commit. Check out this website [gitignore.io](https://www.toptal.com/developers/gitignore) to create your `.gitignore` file, search for `django`, `python`, `venv` and copy the output into the created `.gitignore` file.

```bash
touch .gitignore
```
![Adding .gitignore file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k57i0osxwlpn59phmlyi.png)

- To check whether our setup is working or not, let's run our django development server by running the below command.
```python
py manage.py runserver
```

- After running, you should see our development server started at `localhost:8000`, you will get a warning message that *you have 18 unapplied migration(s)*, for now ignore it.
![Running Django dev server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2fcuu8mue9ce6i7dwzqe.png)

- Press `ctrl + click` on `https://127.0.0.1:8000`, it automatically opens a browser window, you should see the below screen.
![Our website is up & running!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/94wxewpajv0ovvmameo8.png)

- Hooray 🥳!! you have successfully done with django setup. To stop the running server press `ctrl+c` in your terminal.

---
## Running our first webpage

- Before starting, firstly we must know some basic Django terminologies 

	**views** 
	1. They are python classes or functions that receives web request as one of its argument and returns web response.
	3. Response can be a simple HTTP request or HTML template response or HTTP redirect response that redirects user to specific webpage
	4. we write our business logic inside view and put all the views under `views.py`

	**URLs**
	1. we request the specific resource to Django server in terms of URLs
	2. we keep all our URLs under `urls.py`

	**Template**
	1. It is used to render HTML dynamically on our web page along with values passed over the response
	2. It is handled by powerful template engine

<br>

- Go to `codecraze` directory, create a new file called `views.py` where we can put views which serves the respective webpage.
```bash
touch views.py
```
![Project files](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hylzlqgsdon7e56l264u.png)

- Now open your favourite code editor in that folder, search for `views.py` & open it. Lets write our first view which returns our homepage of the website.
```python
#views.py
from django.http import HttpResponse
def index(request):
	"""returns a simple HTTP response as homepage of our codecraze site"""
	return HttpResponse("<h1>CoDeCrAzE</h1><br><h3>Hi!! There 👋</h3>")
```

- search for `urls.py` & open it. Add the below URL which routes our request to the homepage of our website. Make sure you import `views.py`, so that we can request to that view which returns our homepage
```python
# open urls.py under codecraze folder
from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
	path('', views.index, name="home-page"), #homepage of CodeCraze site
]
```

- Once everything is done, Lets start our development server to see our changes, run `python3 manage.py runserver` and type `localhost:8000/` in your new tab of the browser.
![Our Homepage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gssl9roxvy4inqg7rurh.png)

- Cheers 🥂, you have successfully created your homepage. 

- Now let's apply migrations to convert Django models which has been created already for us into DB schema, run `py manage.py showmigrations` to view the migrations to be applied 

![showmigrations](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odx4qiht0ev2dmrelted.png)

- Then run `py manage.py migrate` to migrate already defined Django models. So next time when you start development server, you won't see the migration warnings.
![migrate](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dh8u1ppgqx23lytnlopa.png)

- Make sure you commit all yours changes 😁.


**In the upcoming article, we will implement CRUD functionality where we can create, read, update & delete posts for our blog**

Finally I request you to cover up the basics of [Templates](https://docs.djangoproject.com/en/4.2/topics/templates/) in Django, which will used be in the next section.

Until then, **Peace!!✌🏻**