Django Notes
Django Notes
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.
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.
#######################################
##############################################
##### 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
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
"""
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
##############################################
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
"""
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
##############################################
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.
##### myproject/settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
##############################################
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
"""
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>")
##############################################
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
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>")
##############################################
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>")
##### 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 %}
##############################################