- Django is web framework provides a generic functionality needed for building:
- web applications
- APIs
- web services
- Django used MVT Architecture
mvtArchitecture
- URL dispatcher
- equivalent to the controller in the MVC architecture.
- The URL patterns defined in each app under the project are also included, urls.py:
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ]
- View
- view function reads the path, query, and body parameters included in the client's request If required.
- It uses this data to interact with the models to perform CRUD operations.
- A view can be a user-defined function or a class, You create View definitions in the views.pyfile of the respective app package folder.
- The following code in the view.py file defines the index() view function.
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse("Hello, world.")
- view function reads the path, query, and body parameters included in the client's request If required.
- Model
- a Python class, An app may have one or more model classes, conventionally put in the models.py file.
- Django migrates the attributes of the model class to construct a database table of a matching structure.
- Django's Object Relational Mapper helps perform CRUD operations in an object-oriented way instead of invoking SQL queries.
- The view uses the client's and the model's data and renders its response using a template.
- Template
- a web page containing a mix of static HTML and Django Template Language code blocks.
- You place Template web pages in the templates folder with the .html extension.
- Django's template processor uses any context data from the view inserted in these blocks to formulate a dynamic response.
- The view, in turn, returns the response to the user.
- Django Documentation
- URL dispatcher
- Make sure to have python installed, and update pip version
py -m pip install --upgrade pip
- Create a directory and in the directory create a python venv:
mkdir <directory_name>
cd <directory_name>
py -m venv <env_name>
- To activate venv
source ./<env_name>/Scripts/activate
- To deactivate venv
deactivate
- In the directory, install django with pip
pip install django
- To check installed django version
or
python -m django version
pip list
- In the directory, while venv has activated, run:
django-admin startproject <project_name>
- In the directory, while venv has activated, run:
-
cd <project_name>
python manage.py startapp <app_name>
- In the directory while venv has activated, run:
cd <project_name>
python manage.py runserver
- If the bash responded with:
Watching for file changes with StatReloader
- This mean server successfully launched. You can now open localhost. By default, the development server will be accessible at http://127.0.0.1:8000/ or http://localhost:8000/.
- To stop development server, just hit ctrl+c in bash.
- make sure to have django installed
- in the views.py
from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("Hello World!")
- in the App-level urls.py(If not exists please create one.)
from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), ]
- in the Project-level urls.py
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ]
- in the setting.py
- add "'myapp.apps.MyappConfig'," to the INSTALLED_APPS list.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.MyappConfig', ]
- make sure to have django installed
- in the views.py
from django.shortcuts import render from http.client import HTTPResponse from django.http import HttpResponse def drinks(request, drink_name): drink = { 'mocha' : 'type of coffee', 'tea' : 'type of hot beverage', 'lemonade': 'type of refreshment' } choice_of_drink = drink[drink_name] return HttpResponse(f"<h2>{drink_name}</h2> " + choice_of_drink)
- in the App-level urls.py (If not exists please create one)
from django.urls import path from . import views urlpatterns = [ path('drinks/<str:drink_name>', views.drinks, name="drink_name"), ]
- using instance namespace (If use this please skip step 2 - 4)
- in Project-level urls.py
#in demoproject/urls.py urlpatterns=[ # ... path('demo/', include('demoapp.urls', namespace='demoapp')), # ... ]
- in Project-level urls.py
- adding "app_name = <app_name>" to App-level urls.py
#demoapp/urls.py
from django.urls import path
from . import views
app_name='demoapp'
urlpatterns = [
path('', views.index, name='index'),
]
- we can also use namespace with more than one app
#newapp/urls.py
from django.urls import path
from . import views
app_name='newapp'
urlpatterns = [
path('', views.index, name='index'),
]
- In the Project-level urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('demo/', include('demoapp.urls')),
path('newdemo/', include('newapp.urls')),
]
- To check the url path/route in django shell
python manage.py shell
>>> reverse('demoapp:index')
'/demo/'
>>> reverse('newapp:index')
'/newdemo/'
- In views.py
from django.http import HttpResponsePermanentRedirect from django.urls import reverse def myview(request): .... return HttpResponsePermanentRedirect(reverse('demoapp:login'))
- Using namespace in the url tag
- without using namespace
<form action="/demoapp/login" method="post"> #form attributes <input type='submit'> </form>
<form action="{% url 'login' %}" method="post"> #form attributes <input type='submit'> </form>
- using namespace
<form action="{% url 'demoapp:login' %}" method="post"> #form attributes <input type='submit'> </form>
- Basic error handling (in views.py)
or
from django.http import HttpResponse, HttpResponseNotFound def my_view(request): # ... if condition==True: return HttpResponseNotFound('<h1>Page not found</h1>') else: return HttpResponse('<h1>Page was found</h1>')
from django.http import HttpResponse def my_view(request): # ... if condition==True: return HttpResponse('<h1>Page not found</h1>', status_code='404') else: return HttpResponse('<h1>Page was found</h1>')
- Raise error handling (in views.py)
from django.http import Http404, HttpResponse from .models import Product def detail(request, id): try: p = Product.objects.get(pk=id) except Product.DoesNotExist: raise Http404("Product does not exist") return HttpResponse("Product Found")
- Custom page error handling (in views.py)
- First in settings.py set DEBUG to FALSE and add '*' to the ALLOWED_HOSTS to include all possible hosts.
#settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG=FALSE ALLOWED_HOSTS = ['*']
- ...
- First in settings.py set DEBUG to FALSE and add '*' to the ALLOWED_HOSTS to include all possible hosts.
- Exception Classes
- ObjectDoesNotExist: All the exceptions of the DoesNotExist are inherited from this base exception.
- EmptyResultSet: This exception is raised if a query does not return any result.
- FieldDoesNotExist: This exception is raised when the requested field does not exist.
try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return HttpResponse("Field Does not exist")
- MultipleObjectsReturned: When you expect a certain query to return only a single object, however multiple objects are returned. This is when you need to raise this exception.
- PermissionDenied: This exception is raised when a user does not have permission to perform the action requested.
def myview(request): if not request.user.has_perm('myapp.view_mymodel'): raise PermissionDenied() return HttpResponse()
- ViewDoesNotExist: This exception is raised by django.urls when a requested view does not exist, possibly because of incorrect mapping defined in the URLconf.
- Django’s Form API
def myview(request): if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): #process the form data else: return HttpResponse("Form submitted with invalid data")
- Custom page error handling (in views.py)