Last active
May 31, 2019 06:31
-
-
Save Horopter/bf7676b97a886385bdc4badb0ea027d8 to your computer and use it in GitHub Desktop.
Django CheatSheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--------------------- SETUP ----------------------- | |
1. Download Python 3.5 | |
2. Update Path variables on Windows Path. | |
3. Install Cmder and run as Admin | |
4. Install Pycharm | |
5. $easy_install django | |
6. $easy_install virtualenv | |
7. django-admin startproject Santosh // Santosh is project name | |
8. Never edit manage.py, NEVER! | |
9. Setup USER and MASTER env variable PYTHONPATH "c:\users\horopter\appdata\local\programs\python\python35-32\lib\site-packages\django-1.10.3-py3.5.egg" | |
10. $easy_install virtualenv | |
11. cd in the folder Santosh having manage.py and $python manage.py runserver to launch at localhost:8000 [just like laravel] | |
12. $python manage.py migrate // if asked initially, else skip. | |
13. $python manage.py startapp music | |
----------------------- URLS MANAGEMENT -------------------- | |
1. In Santosh\urls.py | |
from django.conf.urls import url,include | |
from django.contrib import admin | |
urlpatterns = [ | |
url(r'^admin/', admin.site.urls), | |
url(r'^music/', include('music.urls')), | |
] | |
2. In music\urls.py | |
from django.conf.urls import url | |
from . import views | |
urlpatterns = [ | |
url(r'^$', views.index, name='index'), | |
] | |
3. In views.py | |
from django.shortcuts import render | |
from django.http import HttpResponse | |
# Create your views here. | |
def index(request): | |
return HttpResponse('<h1>This is a http response.</h1>') | |
-------------------- DATABASE SETUP ------------------- | |
1. Santosh\settings.py | |
Check for DATABASES section for changing Database Engine | |
-------------------- MODEL CREATION --------------------- | |
1. music\models.py | |
from __future__ import unicode_literals | |
from django.db import models | |
# Create your models here. | |
class Album(models.Model): | |
artist = models.CharField(max_length=256) | |
album_title = models.CharField(max_length=512) | |
genre = models.CharField(max_length=100) | |
album_logo = models.CharField(max_length=100) | |
created_at = models.DateTimeField(auto_now_add=True) | |
updated_at = models.DateTimeField(auto_now=True) | |
class Song(model.Model): | |
album = models.ForeignKey(Album,on_delete=models.CASCADE) | |
file_type = models.CharField(max_length=10) | |
song_title = models.CharField(max_length=256) | |
created_at = models.DateTimeField(auto_now_add=True) | |
updated_at = models.DateTimeField(auto_now=True) | |
2. Add 'music.apps.MusicConfig', to InstalledApps sections in Santosh\settings.py | |
3. python manage.py makemigrations music | |
4. python manage.py migrate | |
----------------------- DATABASE API ----------------- | |
1. Album.objects.all() gives an array of all objects like select query. | |
2. We can override the behavior by __str__(self) method. | |
3. Album.objects.filter(id=2), Album.objects.filter(artist__startswith='Taylor') | |
4. a = Album(<key>=<value>,...) and a.save() to insert | |
---------------------- ADMIN CONTROL ------------------ | |
$python manage.py createsuperuser | |
In admin.py of music, add | |
from models import Album | |
admin.site.register(Album) | |
------------------------- ADDING ANOTHER VIEW ----------------- | |
Simple GET request | |
1. url(r'^(?P<id>[0-9]+)/$', views.detail , name='detail') in music\urls.py | |
2. def detail(request,id): | |
return HttpResponse('<h2>Details for album id :'+id+' </h2>') in music\views.py | |
-------------------------- RETRIEVING DATA FROM DB --------------- | |
1. In views.py | |
from django.shortcuts import render | |
from django.http import HttpResponse | |
from models import Album | |
# Create your views here. | |
def index(request): | |
all_albums = Album.objects.all() | |
html = '' | |
for album in all_albums: | |
url = '/music/' + str(album.id) + '/' | |
html += '<a href="'+url+'">'+album.album_title+'</a><br/>' | |
return HttpResponse(html) | |
def detail(request,id): | |
return HttpResponse('<h2>Details for album id :'+id+' </h2>') | |
----------------------------- TEMPLATES INTRODUCTION ---------------- | |
1. In views.py | |
from django.shortcuts import render | |
from django.http import HttpResponse | |
from models import Album | |
from django.template import loader | |
# Create your views here. | |
def index(request): | |
all_albums = Album.objects.all() | |
context = { | |
'all_albums' : all_albums, | |
} | |
template = loader.get_template('music/index.html') | |
return HttpResponse(template.render(context,request)) | |
#or return render(request,'music/index.html',context) instead of above two lines | |
def detail(request,id): | |
return HttpResponse('<h2>Details for album id :'+id+' </h2>') | |
2. Code changes are below : add a folder templates in music folder. Within templates add music folder and within that, add index.html | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body> | |
{%if all_albums%} | |
{%for album in all_albums%} | |
<ul> | |
<li> | |
<a href="/music/{{album.id}}">{{album.title}}</a> | |
</li> | |
</ul> | |
{%endfor%} | |
{%else%} | |
<h1>You don't have any albums</h1> | |
{%endif%} | |
</body> | |
</html> | |
------------------------- RAISING A 404 ERROR ----------------- | |
1. In views.py | |
from django.shortcuts import render | |
from django.http import HttpResponse,Http404 | |
from models import Album | |
from django.template import loader | |
# Create your views here. | |
def index(request): | |
all_albums = Album.objects.all() | |
context = { | |
'all_albums' : all_albums, | |
} | |
template = loader.get_template('music/index.html') | |
return HttpResponse(template.render(context,request)) | |
#or return render(request,'music/index.html',context) instead of above two lines | |
def detail(request,id): | |
try: | |
album = Album.objects.get(pk=id) | |
except Album.DoesNotExist: | |
raise Http404("It doesn't exist") | |
return render(request, "music/detail.html", {'album' : album}) | |
****** To see standard 404 page, set DEBUG = false in settings.py |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment