2026-09-03 19:05

Status:


DADSD - Module 4 - Consolidate and Deploy Your Django App

==Consolidate and Deploy Your Django App

  • Class-Based and Generic Class Views:
    • Function Based Views are basically the original views that exist inside of django, these are just regular python functions that essentially map over to a URL and are able to send back a given HTTP response on that endpoint
    • they allow for the use of things like templates in order to do things like access data or send back dynamic html content
    • Class Based Views- These are similar and were added to Django as a means of extending the reusability and ability of regular views
    • Either way, a view is either a python class or function that is callable
    • Pasted image 20260903191355.png
    • A simple class based view, a function one, is generally pretty hard to extend or customize because of the strict structure requirements that are needed for it to be used as a Django View
    • It is also a function and so it gets a bit muddled with how much you can really add into it
    • However, with something like a class based view from above, you can basically just create a class that subclasses the Django View baseclass, then you can overwrite some basic methods like the above get or post
    • These are then called whenever that specific request would get hit
    • This allows you to kind of split up your logic a little bit better based on what kind of end point is hitting what with whichever kind of request
    • Generally speaking it allows for you to extend out the objects you created
    • Pasted image 20260903191655.png
    • You still need to configure the given route/endpoint for the function that you want to get hit, although it is a class now not a function
    • Either way, it is pretty much the same way you would assign a view, the only real difference is that you use the as_view() method which gets inherited from the base view class from Django I would assume
    • Pasted image 20260903191855.png
    • This is basically sort of the base Django View class in which you can inherit from whenever you want to set up a class based view.
    • So basically, whenever you call this method inside of the URL callable, what it does is basically define a new inner view method which gets returned based on whatever content was in your view class
    • This way the class you passed in basically becomes a regular view function, and Django can handle it with ease
    • Pasted image 20260903192125.png
    • Pasted image 20260903192155.png
    • For a developer and in the development environment, Django basically helps out to create a simple Generic class-based view which is built-in and used for things like debugging and printing out information
    • Generally the Pros of using Function-Based views are that is is
      • Simple and Easy to understand
      • Gives you explicit code that you can write without any structure
      • Mainly used for a built of a very specific function to handle an obscure task
    • The Downsides Include:
      • They are difficult to extend or reuse
      • They also handle requests using conditional if/else statements, which makes your code far less readable and a pain in the ass to work with
  • Django Authentication System:
    • Authentication and Authorization is the process of making sure that someone is who they say that they are based on things like a username and password, or several other metrics of identify and verifying your identity

    • Authorization then is the process of making sure that this someone, after proving who they are, has in fact gotten permission and access to view whatever data it is that they are trying to view

    • See IT Security - Defense Against The Digital Dark Arts for more information

    • Pasted image 20260903195746.png

    • Django User Objects these are basic models (database tables) that basically provide basic information about users, like things including password, id, username, email, and other metadata

    • These objects can then be linked and used with other forms of models in order to properly authenticate and authorize a given account to let them perform whatever action they would want

    • Pasted image 20260903195834.png

    • Pasted image 20260903200002.png

    • This is basically just a simple not fully complete HTML template that can show how you can set up a way for someone to input their password and username credentials, so you can then eventually check through them

    • Once the force is completed, you will basically send a post request over to the url onlinecourse:login and what not

    • There is also an above oh how it looks, and is basically a simple front-end

    • Pasted image 20260903200020.png

    • You then have something like this, which would basically get the two pieces of data in the form of a user and a password from the request in the form

    • Then, after this request is queried, you are able to authenticate these people using either a built in function or your own method, letting you then basically allow them to access whatever it is that they are trying to access

    • This is a basic backend

    • Pasted image 20260903200502.png

    • Each time that a user is logged in, Django creates a new session inside of the Django Session Framework, where stateful data for the authenticated user stored while visiting the site

    • sessionid is also stored as a browser cookie, allowing for cool reference of which user is being identified by this unique session idea every single time they are on

    • You can then use this cookie to basically access a lot of this basic information, like the session id and items and all the other good stuff you wanna access

    • If the user is in face authenticated, then you should be able to see things like a valid session id, and then a dictionary with an actual value inside of it, this is however the opposite, and all of these values would be empty if the user is NOT authenticated

    • To then log the user out is very simple as well, you can just call a logout() method that is provided to you by the Django Framework

    • You can also use this general set up for something like registration, which allows for you to basically insert the new data into a database, its pretty simple stuff really

  • Bootstrap:
    • Pasted image 20260903212808.png

    • Bootstrap is a free front end framework that is designed to facilitate web app development.

    • It provides a tone of common HTML/CSS, simplifying Django template development.

    • You can see more about it inside of the Common CSS Elements helper doc, where it basically is listed as one of the frameworks alongside tailwind I believe

    • To integrate bootstrap CSS style classes without downloading bootstrap, you can actually just add in an internet link in the style portion of your HTML code something like https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css into the head element

    • Now you can basically start using a bunch of the different classes that boot strap would offer you in order to spice up your HTML documents in Django

      Pasted image 20260903213027.png

    • Pasted image 20260903213109.png

    • Pasted image 20260903213146.png

    • Pasted image 20260903213230.pngPasted image 20260903213243.png

    • Pasted image 20260903213307.png

    • They basically just give you a bunch of different code examples man on how to use bootstrap to develop their example ass application, its basic enough

  • Django Static Files:
    • Pasted image 20260903214219.png
    • If you want to add in static files over to your application, you first need to actually set up folder for them inside of your project, this being things like a solid template folder as well as given things like images and styling and all other things
    • This is both just good practice, and then also a good way for Django to recognize whatever the fuck you want if you have multiple different apps in one environment
    • Pasted image 20260903214539.png
    • You generally store static files in a folder inside of the directory of your application in it’s own static directory
    • You can also however reference outside static files using the STATICFILES_DIRS list inside of the settings.py file in the root directory of your project
    • All of these given things are then given to the STATICFILE_FINDERS which are basically just able to find the relative or absolute path of the given static file and use it where you need to, and serve them for you
    • Pasted image 20260903214734.png
    • Pasted image 20260903214747.png
    • When you deploy your application onto some remote server, then you might eventually want to actually migrate all of your files into a single location, making it easier to manage
    • Django basically provides a staticfiles (what the fuck does it not provide then damn), app which does exactly that, collects them all into a single directory specified with the STATIC_URL
  • Deploy Your Django Apps:
    • You use the runserver command inside of a local command line in order to start a minimal web server on your given host device, which runs your code and sets it all up right
    • The thing is, you generally need to deploy your code over to a remote web server somewhere else if you want it to actually be in production
    • The issue is the that Apache HTTP and Nginx are not written in python, and are not meant to naively work with python code, so Django needs other interfaces to be able to communicate
    • Pasted image 20260903215502.png
    • The Web Server Gateway Interface (WSGI) is the main interface that allows for synchronous python code to communicate between web servers and applications
    • The use of this in Django would basically create a wsgi.py file, declaring an application callable by default to make a Django Application work with wsgi
    • These wsgi servers then try to find this application callable, and use it as entry point to communicate with your application
    • Basically, it looks like you need to rely on these third party applications to have your code run
    • There is also the Asynchronous Server Gateway Interface (ASGI), which as the name suggests, is mainly different in that the code can be asynchronous in structure, this creates the asgi.py file and callable, and works very similar to how wsgi works
    • Web Server Deployment- is basically a pain in the ass, and I would know, I deployed the Midas cloud portal front end and backend today using docker, and it sucked
    • You need to keep in mind a lot of things during your deployment, like networking, databases, servers, and runtimes so your app works cohesively together through a secure layer
    • A lot of this has been made a lot easier through IaaS or even PaaS, which abstracts out a lot of the infrastructure that you would have to set up and work with
    • You can use something like a hosting solution using the cloud
    • You can use something like a virtual machine, install the needed software and whatever software you need like nginx or whatever, and then configure the environment, make sure your front-end and back-end can communicate, and then open her up to the world based on your domain
    • Then boom, you got yourself a website
    • You can also do something like Heroku which basically just takes your code, figures out what the fuck to do, and does it for you
    • You can also do what I did with compose, where I basically set up a docker containers package and deployed it with compose

==Summary

  • Both function-based and class-based views are Python functions.
  • When you build a class-based view, you define a class subclassing the Django View base class. Then you access some standard methods such as Get or Post. Next, you implement your logic to handle HTTP requests.
  • To speed up development and solve common tasks, Django provides some built-in view classes called generic-based views for developers to reuse.
  • Authentication is validating users’ identities using credentials such as username and password.
  • After users are authenticated, authorization will check the users’ access permissions for resources such as databases.
  • In Django, a user model is created to handle authentication and to work with other models, such as groups and permissions, to handle authorization.
  • Developers can extend the User model to define application-specific users, such as instructors or learners inherited from the User model.
  • Bootstrap, a free web front-end framework, facilitates web app development.
  • Bootstrap provides many HTML and CSS templates to simplify Django template development.
  • If you want to use Bootstrap CSS style classes without downloading Bootstrap, add a link to the latest Bootstrap version into the head element of your HTML template.
  • To add static files to your apps, you first create folders for different static files, such as HTML templates, images, or CSS files.
  • Under each folder to hold static files, you create a subfolder using the same app name. This creates namespacing to uniquely refer to static files that use the same name across multiple apps in a Django project. 
  • Django provides a set of STATICFILES_FINDERS for locating the static files in an app. It also provides a staticfiles app to collect all static files in a single directory when an app is deployed.
  • To deploy reliable, scalable, and maintainable Django apps, you need to deploy them on web servers. 
  • Since most web servers are not written in Python, Django apps need extra interfaces to talk to web servers.
  • The Web Server Gateway Interface, or WSGI, is the main Python standard for communicating between Web servers and applications.
  • The Django app supports the Asynchronous Server Gateway Interface, another web server interface.
  • Infrastructure as a Service and Platform as a Service offering allows you to focus on your app development and deploy apps without worrying about the underlying Infrastructure and platform.

==Cheat Sheet

Package/ MethodDescriptionCode Example
ListView:Displays a list of objects.class MyListView(ListView): 

    model = MyModel 

    template_name = ‘my_template.html’ 

    context_object_name = ‘object_list’  # default: object_list
DetailViewDisplays details of a single object.class MyDetailView(DetailView): 

    model = MyModel 

    template_name = ‘my_template.html’ 

    context_object_name = ‘object’  # default: object 

    pk_url_kwarg = ‘my_model_id’  # default: pk
CreateViewDisplays a form to create a new object.class MyCreateView(CreateView): 

    model = MyModel 

    template_name = ‘my_template.html’ 

    fields = ‘all’  # or specify a list of fields
UpdateViewDisplays a form to update an existing object.class MyUpdateView(UpdateView): 

    model = MyModel 

    template_name = ‘my_template.html’ 

    fields = ‘all’  # or specify a list of fields 

    pk_url_kwarg = ‘my_model_id’  # default: pk
DeleteViewDisplays a confirmation page to delete an object.class MyDeleteView(DeleteView): 

    model = MyModel 

    template_name = ‘my_template.html’ 

    success_url = ‘/success-url/’ 

    pk_url_kwarg = ‘my_model_id’  # default: pk
Basic View FunctionFunction-based view that returns “Hello, World!” 

From Django.http import HttpResponse
def my_view(request): 

    # Your view logic here 

    return HttpResponse(“Hello, World!”)
Render a TemplateFunction-based view to render a template with context. 

From django.shortcuts import render
def my_template_view(request): 

    context = {‘variable’: value} 

    return render(request, ‘my_template.html’, context)
Redirect to a URLFunction-based view to redirect to a specific URL. 

From django.shortcuts import redirect
def my_redirect_view(request): 

    return redirect(‘url_name_or_path’)
Handle a Form SubmissionFunction-based view to handle form submission. 

From django.shortcuts import render
def my_form_view(request): 

    if request.method == ‘POST’: 

        # Process the form data here 

    else: 

        # Display the form 

    return render(request, ‘my_form_template.html’, context)
Handle URL ParametersFunction-based view that accesses URL parameters.def my_param_view(request, param): 

    # Access the ‘param’ value from the URL
Protecting Views (Restrict Access) using @login_required DecoratorFunction-based view protected with login_required decorator. 

From django.contrib.auth.decorators import login_required
@login_required 

def my_protected_view(request): 

    # Your view logic here
Bootstrap CSSLink to include Bootstrap CSS in the base template.Add the following link to the section of your base template (usually base.html): 

Bootstrap JavaScriptScript tag to include Bootstrap JavaScript library.Include the Bootstrap JavaScript library at the end of the section to enable certain features (for example, dropdowns, modals): 

Bootstrap classes and componentsCreate visually appealing and responsive web pages without having to write CSS styles manually.Click Me
Configuration – Static filesDjango settings for static files configuration.In your Django settings (settings.py), define the following settings: 

STATIC_URL = ‘/static/studio/edx.org-next/’  # URL to access static files 

STATICFILES_DIRS = [os.path.join(BASE_DIR, ‘static’)]  # Directory to look for static files
Configuration – Installed appsDefines a list of all the applications installed in the project.Add ‘django.contrib.staticfiles’ to your INSTALLED_APPS in settings.py: 

INSTALLED_APPS = [ 

    # … 

    ‘django.contrib.staticfiles’, 

    # … 

]
Configuration – App DirsA configuration option used within the TEMPLATES setting. When set to TRUE, Django will look for template files within the app directories.Make sure the APP_DIRS setting is set to True in the TEMPLATES list. This allows Django to look for static files within the apps’ directories. 

TEMPLATES = [ 

    { 

        # … 

        ‘APP_DIRS’: True, 

        # … 

    }, 

]
Usage – Static contentCode to style the HTML templates and provide interactivity to web pages. 

 

Collecting static filesWhen deploying your project, you need to collect all static files into a single location.python manage.py collectstatic 

STATIC_ROOT = os.path.join(BASE_DIR, ‘staticfiles’)

References