So I started Django today. My first impression is that it’s definitely better suited for larger projects than Flask is. Pretty much everything gets done in one file in Flask, which can get real messy real fast. Django, on the other hand, is designed with the MVC paradigm in mind, so everything is separated out into a nice, structured hierarchy of files. In fact, there are so many separate files and folders to keep track of that it was a tad overwhelming at first. Right off the bat, instructor Fiaz had me memorize the startup process for the beginning setup of a new Django process and drill it in over and over again until I was able to do the whole process in under two minutes. I guess I can even list them here because why not.
- Enter your Django virtual environment
- Run the command
django-admin startproject projectNameHerewherever you want your project folder to be located
projectNameHeredirectory and create the apps folder with
- Run the command
python ../manage.py startapp appNameHere
- Open the project folder in atom with
atom ..(or use some other text editor)
- Navigate to the
settings.pyfile in the
- Add the new app
'apps.appNameHere',to the top of the
INSTALLED_APPSlist. And don’t forget the comma! I got errors for that quite a few times, lol.
- Navigate to
urls.pyin the same folder, add
includeto the import line right after
urlso that it looks like
from django.conf.urls import url, include.
- Add another pattern for django to listen for in the
url(r'^', include('apps.appNameHere.urls')),. This file we’re including doesn’t exist yet but we’ll add it soon.
- Next, navigate to the views.py in the appNameHere folder inside of the apps folder you created earlier.
- In views.py, all of your controller methods need to be defined here. Just to get started I like to import HttpResponse and define my index method like so:
from django.shortcuts import render, HttpResponse def index(request): return HttpResponse('Hello World')
- Now we need to create that urls file. Inside the appNameHere folder, create a new file called urls.py and paste this in there:
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index) ]
- And now we should be good to go! Go back to the terminal and run
python ../manage.py runserverand go to localhost:8000 in your web browser!
This little explanation took longer than I thought it would! I really need to figure out some better way of putting code into wordpress posts… Anyways, after this initial setup, the project is ready to be filled up with more functionality. There are a couple more steps to add when rendering actual HTML templates rather than just simple HttpResponses, but this is the basic setup that needs to happen for every project. I’m liking Django so far and I’m excited to translate more of my flask projects over. I’m gonna really dig in these next few days and do my best to prepare for the belt exam. I’m really looking forward to project week, so I better not fail it, lol!