0% found this document useful (0 votes)
34 views

Django Notes

The document provides an overview of the Django web framework including its history, features, sites that use it, and how to install, create projects and apps, handle templates, static files, redirects, cookies, caching, and sessions.

Uploaded by

Global EDX
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Django Notes

The document provides an overview of the Django web framework including its history, features, sites that use it, and how to install, create projects and apps, handle templates, static files, redirects, cookies, caching, and sessions.

Uploaded by

Global EDX
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

Django Web

Framework:
===================
visit
https://www.djangoproject.com/

Intro:
====
Django is a Python based Web Framework used for easy web development.

History:
======
Django was originally developed at the web department of "Lawrence Journal-World
Newspapers, Kansas, USA.

Around Sept, 2003. Developers Adrian Holovaty and Simon Willison developed Django
Web Framework.

The framework was named after guitarist Django Reinhardt.

Django is now run by an international team of volunteers. DSF.

Features:
=======
#######################################
Fully loaded -- Django takes care of user authentication, content administration,
site maps, RSS feeds, and many more tasks, right out of the box.
#######################################
Fast Apps -- Designed to complete the app as quickly as possible.
#######################################
Open Source -- Free and Open Source
#######################################
Secure -- Cross site request forgery (CSRF) Technique, HTTPS/SSL Protocols
#######################################
Scalable -- Sites built on Django have survived traffic spikes of over 50 thousand
hits per second.
#######################################
Versatile -- Django is used to build all sorts of things like content management
systems, social networks and scientific computing platforms.
#######################################

Sites built using Django


===============
Bitbucket, Instagram, Mozilla Firefox, Pinterest, YouTube, DropBox, NASA, The
Washington Post, National Geographic.

##### To verify the python version


python --version

##### To install django


pip install django

##### To verify the django version


django --version

##### To start a project


django-admin startproject <project_name> .
##### To start an app
python manage.py startapp <app_name>

##### By default django uses sqlite3 database.


##### If you create/edit any models. Changes to those models should be migrated.
python manage.py makemigrations
python manage.py migrate

##### To create a super user account


python manage.py createsuperuser

##### To start the development server


python manage.py runserver

##############################################
##### Add your app name to INSTALLED_APPS list from settings.py

INSTALLED_APPS = [
...
'myapp',
]

##############################################
##### Templates
##### Put your .html files into a directory called 'templates'
##### This templates folder should be under your BASE_DIR (proj1)
##### Now update your TEMPLATES list from settings.py

'DIRS': [os.path.join(BASE_DIR, 'templates'),],


##############################################
##### Static files (CSS, JavaScript, Images, Videos)
##### Put your Static Files into a directory called 'static'
##### This static folder should be under your BASE_DIR (proj1)
##### Now update your settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

##### To collect the static files into static root directory


python manage.py collectstatic
##############################################

##### Django Redirect


##### myapp/urls.py

from django.urls import path


from . import views

urlpatterns = [
path('', views.home, name='home'),
path('contact/', views.contact, name='contact'),
path('about/', views.about, name='about'),
path('login/', views.login, name='login'),
path('redirect_page/', views.redirect_page, name='redirect_page'),
path('redirect_site/',
views.RedirectClass.as_view(url='https://www.photographyblog.com/'),
name='redirect_site'),
]
##### myapp/views.py
from django.shortcuts import render, redirect, HttpResponse
from django.views.generic.base import RedirectView

# Create your views here.

"""
def contact(request):
context={}
return render(request, 'contact.html', context)
"""
def home(request):
return HttpResponse("<html><body><h1> WELCOME TO HOME PAGE.
</h1></body></html>")

def contact(request):
return HttpResponse("<html><body><h1> WELCOME TO CONTACT PAGE.
</h1></body></html>")

def about(request):
return HttpResponse("<html><body><h1> WELCOME TO ABOUT PAGE.
</h1></body></html>")

def login(request):
return HttpResponse("<html><body><h1> WELCOME TO LOGIN PAGE.
</h1></body></html>")

def redirect_page(request):
return redirect('/login')

class RedirectClass(RedirectView):
pass

##############################################

##### Django Cookie Handling


##### myapp/urls.py

from django.urls import path


from . import views

urlpatterns = [
path('', views.home, name='home'),
path('contact/', views.contact, name='contact'),
path('about/', views.about, name='about'),
path('setcookie/', views.setcookie, name='setcookie'),
path('getcookie/', views.getcookie, name='getcookie'),
path('delcookie/', views.delcookie, name='delcookie'),
]

##### myapp/views.py
from django.shortcuts import render, redirect, HttpResponse
from django.views.generic.base import RedirectView

# Create your views here.

"""
def contact(request):
context={}
return render(request, 'contact.html', context)
"""
def home(request):
return HttpResponse("<html><body><h1> WELCOME TO HOME PAGE.
</h1></body></html>")

def contact(request):
return HttpResponse("<html><body><h1> WELCOME TO CONTACT PAGE.
</h1></body></html>")

def about(request):
return HttpResponse("<html><body><h1> WELCOME TO ABOUT PAGE.
</h1></body></html>")

def setcookie(request):
responss = HttpResponse("<h1>COOKIES CREATED.</h1>")
responss.set_cookie('cookiekey_NAME', 'cookievalue_ANIL', max_age =
2*365*24*60*60 ) #2_years
responss.set_cookie('cookiekey_EMAIL', '[email protected]', max_age =
2*365*24*60*60 ) #2_years
responss.set_cookie('cookiekey_GENDER', 'cookievalue_MALE', max_age =
2*365*24*60*60 ) #2_years
return responss

def getcookie(request):
show = request.COOKIES['cookiekey_NAME']+",
"+request.COOKIES['cookiekey_EMAIL']+", "+request.COOKIES['cookiekey_GENDER']
responss = "<center> <h1>Showing Cookie Values
</h1><br><h1>{0}</h1></center>".format(show)
return HttpResponse(responss)

def delcookie(request):
responss = HttpResponse("<h1>COOKIES DELETED.</h1>")
responss.set_cookie('cookiekey_NAME')
responss.set_cookie('cookiekey_EMAIL')
responss.set_cookie('cookiekey_GENDER')
return responss

##############################################

##### Django Caching

Setting up the cache


====================
The cache system requires a small amount of setup. Namely, you have to tell it
where your cached data should live � whether in a database, on the filesystem or
directly in memory(Memcached). This is an important decision that affects your
cache�s performance; yes, some cache types are faster than others.

Your cache preference goes in the CACHES setting in your settings file.

Memcached
=========
The fastest, most efficient type of cache supported natively by Django, Memcached
is an entirely memory-based cache server, originally developed to handle high loads
at LiveJournal.com and subsequently open-sourced by Danga Interactive. It is used
by sites such as Facebook and Wikipedia to reduce database access and dramatically
increase site performance.

Memcached runs as a daemon and is allotted a specified amount of RAM. All it does
is provide a fast interface for adding, retrieving and deleting data in the cache.
All data is stored directly in memory, so there�s no overhead of database or
filesystem usage.

After installing Memcached itself, you�ll need to install a Memcached binding.


There are several Python Memcached bindings available; the two most common are
python-memcached and pylibmc.

To use Memcached with Django:

Set BACKEND to django.core.cache.backends.memcached.MemcachedCache or


django.core.cache.backends.memcached.PyLibMCCache (depending on your chosen
memcached binding)
Set LOCATION to ip:port values, where ip is the IP address of the Memcached daemon
and port is the port on which Memcached is running, or to a unix:path value, where
path is the path to a Memcached Unix socket file.
In this example, Memcached is running on localhost (127.0.0.1) port 11211, using
the python-memcached binding:

##### myproject/settings.py

CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}

##############################################

##### Django Sessions


##### myapp/urls.py

from django.urls import path


from . import views

urlpatterns = [
path('', views.home, name='home'),
path('contact/', views.contact, name='contact'),
path('about/', views.about, name='about'),
path('create_session/', views.create_session, name='create_session'),
path('access_session/', views.access_session, name='access_session'),
path('delete_session/', views.delete_session, name='delete_session'),
]

##### myapp/views.py
from django.shortcuts import render, redirect, HttpResponse
from django.views.generic.base import RedirectView

# Create your views here.

"""
def contact(request):
context={}
return render(request, 'contact.html', context)
"""
def home(request):
return HttpResponse("<html><body><h1> WELCOME TO HOME PAGE.
</h1></body></html>")

def contact(request):
return HttpResponse("<html><body><h1> WELCOME TO CONTACT PAGE.
</h1></body></html>")

def about(request):
return HttpResponse("<html><body><h1> WELCOME TO ABOUT PAGE.
</h1></body></html>")

def create_session(request):
request.session['username'] = 'testuser'
request.session['password'] = 'testpassword'
return HttpResponse("<h1>mywebsite<br> the session is set</h1>")

def access_session(request):
response = "<h1>Welcome to Sessions of mywebsite</h1><br>"
if (request.session.get('username') and request.session.get('password')):
response += "UserName : {0} <br>".format(request.session.get('username'))
response += "Password : {0} <br>".format(request.session.get('password'))
return HttpResponse(response)
else:
return redirect('/create_session')

def delete_session(request):
try:
del request.session['username']
del request.session['password']
except KeyError:
pass
return HttpResponse("<h1>mywebsite<br>Session Data cleared</h1>")

##############################################

##### Django Form Handling and Validation


##### myapp/urls.py

from django.urls import path


from . import views

urlpatterns = [
path('', views.home, name='home'),
path('contact/', views.contact, name='contact'),
path('about/', views.about, name='about'),
path('regform/', views.regform, name='regform'),
]

##### myapp/views.py
from django.shortcuts import render
from . import forms

# Create your views here.


"""
def contact(request):
context={}
return render(request, 'contact.html', context)
"""
def home(request):
return HttpResponse("<html><body><h1> WELCOME TO HOME PAGE.
</h1></body></html>")

def contact(request):
return HttpResponse("<html><body><h1> WELCOME TO CONTACT PAGE.
</h1></body></html>")

def about(request):
return HttpResponse("<html><body><h1> WELCOME TO ABOUT PAGE.
</h1></body></html>")

#mywebsite #Form #View Functions


def regform(request):
form = forms.SignUp()
if request.method == 'POST':
form = forms.SignUp(request.POST)
html = 'Congratulations! Your form request successfully processed.'
if form.is_valid():
html = "The Form is Valid. \n" + html
else:
html = 'welcome for first time'
return render(request, 'signup.html', {'html': html, 'form': form})

##############################################

##### Django File Uploads


##### myproject/settings.py
##### Add app to INSTALLED_APPS list

INSTALLED_APPS = [
...
'myapp',
]

TEMPLATES = [
...
'DIRS': [os.path.join(BASE_DIR, 'templates'),],
...
]

STATIC_URL = '/static/'
#STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
#STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

##### myproject/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]

##### myapp/urls.py
from django.urls import path
from . import views
from myproject import settings
from django.conf.urls.static import static

urlpatterns = [
path('', views.home, name='home'),
path('contact/', views.contact, name='contact'),
path('about/', views.about, name='about'),
path('create_profile/', views.create_profile, name='create_profile'),
]
if settings.DEBUG:
#urlpatterns += static(settings.STATIC_URL, document_root =
settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

##### myapp/models.py
from django.db import models
# Create your models here.

class User_Profile(models.Model):
fname = models.CharField(max_length=200)
lname = models.CharField(max_length = 200)
technologies = models.CharField(max_length=500)
email = models.EmailField(default = None)
display_picture = models.FileField()
def __str__(self):
return self.fname

##### myapp/admin.py
from django.contrib import admin
from myapp.models import User_Profile
# Register your models here.

admin.site.register(User_Profile)

##### myapp/forms.py
from django import forms
from .models import User_Profile
#mywebsite #File_Upload
class Profile_Form(forms.ModelForm):
class Meta:
model = User_Profile
fields = [
'fname',
'lname',
'technologies',
'email',
'display_picture'
]

##### myapp/views.py
from django.shortcuts import render, HttpResponse
from .forms import Profile_Form
from .models import User_Profile

def home(request):
return HttpResponse("<html><body><h1> WELCOME TO HOME PAGE.
</h1></body></html>")

def contact(request):
return HttpResponse("<html><body><h1> WELCOME TO CONTACT PAGE.
</h1></body></html>")

def about(request):
return HttpResponse("<html><body><h1> WELCOME TO ABOUT PAGE.
</h1></body></html>")

IMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg']


def create_profile(request):
form = Profile_Form()
if request.method == 'POST':
form = Profile_Form(request.POST, request.FILES)
if form.is_valid():
user_pr = form.save(commit=False)
user_pr.display_picture = request.FILES['display_picture']
file_type = user_pr.display_picture.url.split('.')[-1]
file_type = file_type.lower()
if file_type not in IMAGE_FILE_TYPES:
return render(request, 'error.html')
user_pr.save()
return render(request, 'details.html', {'user_pr': user_pr})
context = {"form": form,}
return render(request, 'create.html', context)

##### templates/create.html

<!DOCTYPE html>
<html>
<head>
<title>Make Profile</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<center>
<div class="jumbotron">
<h1 class="display-4">mywebsite Django File Uploading</h1>
{% block replace %}
<p class="lead">To make a user profile and upload the files fill
this form</p>
<hr class="my-4">
<form method="POST" enctype="multipart/form-data">
<!-- Very Important csrf Token -->
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" class="btn btn-primary btn-lg"
name="register">
</div>
</center>
{% endblock %}
</body>
</html>

##### templates/details.html
{% extends 'create.html' %}
{% block replace %}
<CENTER>
<div class="jumbotron">
<h1 class="display-4">Welcome to mywebsite<br>Hello {{ user_pr.fname }}</h1>
<p class="lead">its an awesome profile picture</p>
<hr class="my-4">
<img src="{{ user_pr.display_picture.url }}" class="image_responsive"
height="100px" width="100px">
<p>
{{ user_pr.display_picture.url }}<BR>
You have learned some awesome technologies like {{ user_pr.technologies }}</p>
</div>
</CENTER>
{% endblock %}

##### templates/error.html
{% extends 'create.html' %}
{% block replace %}
<CENTER>
<h1 style = 'border: 5px red solid;'> hello, you have uploaded the wrong file
type.</h1>
</CENTER>
{% endblock %}

##############################################

You might also like