2026-09-02 15:49

Status:


DADSD - Module 3 - Full Stack Django Development

==Full-Stack Django Development

  • Django Model-View-Template (MVT) Pattern:
    • Pasted image 20260902155602.png
    • MVC divides your application into THREE components
      • Model, which access and manipulates data, but does NOT present the data, it may have database interfaces like ORM or SQL, and it might use business logic on the data as well
      • View which actually presents the data in a given web page or application, it does so ass HTML/CSS/JS or as JSON or XML or other such items, generally via cURL or a browser or something
      • Controller is the thing that routes all of the data between the model and the view, being the middleman between the two pretty much, letting them communicate
    • The controller basically gets the request for the data from the view, and it does things like authenticates and makes sure that they can access the data that they have requested
    • After doing so, it would send over a CRUD request to the model, and then be able to send that data back over to the view
    • Pasted image 20260902160007.png
    • Django MVT, inside of Django, there is no explict controller item instead, Django itself is actually performing this whole expression
      • Django Model manages data modeling and database mapping to process data
      • Django View then sends CRUD requests to the model and describes which data is presented, but NOT HOW it is presented, it generally delegates to a template that dictates how the data is presented, this is called a Django Template
    • Basically, the client sends a request to the Django Server, the said server then routes over to the Django Viewer which requests and authenticates the data, making a CRUD request over to the Django Model or database, and then sends that data over to the Django template, which decides how the data is rendered, and then renders it back over to the client
    • Django Models are basically classes mapped to database tables, and the Django Model APIs allow developers to perform CRUD operations on objects using the ORM intermediary
    • Developers can then also write business logic in Django model classes as functions to let them mess around with the data
    • Django View is basically a python function, that takes in a web request and then applies whatever the necessary logic is to then send a web response, like Web Page, JSON, error, etc
    • Often times, the view would interact with the model, aka the class or whatever, that is representative of the data-table, to be able to access the data needed and preform whatever requests
    • Django Template is basically something that Django has that lets the program generate dynamic web pages
    • It contains static HTML elements, and then special python code that says HOW the dynamic content of HTML will be generated and rendered
  • Create a Django App:
    • Pasted image 20260902160746.png
    • Django development Process
    • You would create an app in the project, which is a container for django apps and settings
    • You would then add the app to the project, and do everything like map out the URLs, build the actual UI, and set up the models for interacting with the databases
    • You can then, after your main app is up and all good, you can add in all of the extra stuff you would want, like configuration, logging, security, and an Admin site provided by Django
    • You can then deploy it and make sure to keep it up and running basically
    • Pasted image 20260902161100.png
    • A Django Project is basically a Python package that would have inside of it all of the needed settings and modules and dependencies for your Django Application
    • You can init a django project by just going into a CLI and running $django-admin startproject <projectname>
    • There is also a bunch of different intermediary files that are created by Django which allow for you to interact and manage everything like:
      • manage.py which lets you start up the server and then also migrate models and such
      • settings.py contains the configuration for your django application and environment
      • urls.py would then contain all of the URLs that you might have in your project, and the different routing methods that exist within them as well
    • Pasted image 20260902161646.png
    • The above is only the actual django environment though not an actual app or anything of the sort, yet, so you instead add that in yourself
    • This is done using $python manage.py startapp <yourappname> inside of the directory where you have your manage.py and what not
    • Django would automatically create a few different file that are important:
      • admin.py includes everything you would need to create and customize an admin site to manage users
      • models.py contains all of the model classes that you need inside of your ORM structure to interact with a database using classes
      • views.py is the view functions/classes where you would do things like handling web requests and stuff
      • urls.py is once again the URL declarations and routing for the app
      • app.py would be the actual application configurations, its basically a class and what not where you set up the actual app I think
      • migrations is a directory that would hold all of the model migration scripts for interacting with the models
    • Pasted image 20260902161803.png
    • Just having your application inside of the directory does not actually include it to the given project though, no, instead you need to basically include the application inside of your Django Project
    • This way the two are connected, and this would be done inside of the settings.py folder and what not
    • The OnlinecourseConfig in the above example is basically a configuration class that represents the app that was created above
    • Pasted image 20260902161919.png
    • This way, now that you have your actual application plugged in, you can set up your database for it, also inside of the settings.py file, where in which you basically just update the dictionary with a new entry for the kind of database that you are going to be using
    • Pasted image 20260902162017.png
    • So to create a model (for ORM interaction with the database), you basically create the python class representative of the table inside of models.py
    • After doing so, you are then able to actually connect it using the Django ORM by calling python manage.py makemigrations <coursename> at which point this
    • Would then run the SQL query code to create the new table with the things that you had described under the actual migrations directory, making it an official connect to a database
    • Pasted image 20260902162420.png
    • Now that you have a model though, you need some way to interact with it, which is where the views would then come in
    • You would basically create a view by defining a new function under views.py, and all of the import django.http and .models integration so that way your view is able to actually communicate with your model
    • You can then define whatever logic you want under this function and then return the request by connecting it over to your template you create
    • Pasted image 20260902163016.png
    • There is a glaring issue though of course, there is no routing or anything of the sort for the user to be able to see or access specific information
    • This way, you need to set up a urls.py inside of your application and then add in the urlpatterns list.
    • This way you can connect over a view to a specific route, allowing you to name it as well, and this way, whenever that specific route is hit from your domain, then that specific view function is hit
    • Hmmm, so it seems you have to set up some sort of global thing inside of your application and then also actually set that up inside of the main urls.py in the top of the project structure
    • Then, to run the app, you call python manage.py runserver which starts the server on your local host, and you can deploy with docker or kubernetes or whatever it is that you want
  • Django Admin:
    • Pasted image 20260902163337.png
    • (Yeah good fuckin luck bro)
    • Basically, there is a LOT of different relationships between the moving parts of this course application
    • Django does allow for the use of a very powerful admin site which lets the developers manage all of this content very easily without too much code
    • Pasted image 20260902163456.png
    • Django provides a built in admin site to manage content, which can then be used to interact with and manage several different portions of the application
    • This generally I think would work by Django actually looking at all of your different model objects representative of different tables, and then creating this sort of an admin manage that lets you manage that data in each of the tables visually
    • Pasted image 20260902163945.png
    • you first set up this whole admin process by actually creating one in your Django application, using the CLI command python manage.py createsuperuser, and this will ask for credentials like a username, email, & password for this user supers
    • You can then run the server using python manage.py runserver and hit up the local host domain with the route http://127.0.0.1:8000/admin/ and log in with the given credentials you just created
    • You will need to register your models with the admin site which is done by importing them into the admin.py python file, which then allows this admin site to automatically interact with your ORM models
    • Pasted image 20260902164456.png
    • Pasted image 20260902165548.png
    • Then, based on the fields that your ORM models have, Django will automatically create a bunch of widgets that let you interact with the table data, things like adding in new ones, or editing existing entries, and more
    • You are then also able to actually set up different things that you want to an admin to see and have access to, for example if there are fields that you do not want them to be able to explicitly change for whatever reason, then you can do so by just specifying the exact fields you wish to be editable, or have them in a particular order
    • Pasted image 20260902165405.png
    • You can also add in management for related objects inside of your ORM to the admin page as well. This is generally also done inside of the admin.py file, although I might be wrong about that because it looks to be involved inside of the classes itself, but it seems to primarily be done using the inlines = [] variable in which you then put in the table/model you want to reference inside of there
  • Django Views:
    • Django View is basically just a python function that would intake a web request from whatever client like POST, GET, DELETE, UPDATE, or whatever other HTTP request
    • This would then return a web response which is something like an HTML file or a JSON or something like that
    • Basically the standard for back end development, you hit this endpoint, I do something whenever you do, and then I send something back
    • Pasted image 20260902170755.png
    • Generally, it would need an HTTP request object as the first argument, and this is where you would also have something like the metadata for the HTTP request, including whatever data was sent over by the front send as well
    • Either way, you then basically can do things with this request, like check the type, and then return back a template or whatever you would like
    • Notice that the request parameter/object has only read-only metadata, which is things like the method type, or the payload of whatever got sent over
    • In the above code example, whenever the view function is hit, it would check to see if the method of the request is GET, and if it is, it would query the model for a pk=1 value, and then it would send back HTML code with the dynamic object displayed
    • Pasted image 20260902171145.png
    • The main difference from Django backend is that unlike something like Flask or even node, the actual URL or route that a given function pertains too is not defined inside of the function itself
    • Instead, it is actually defined in the urls.py folder, in which you set up the specific route, and the view that it connects two
    • Pasted image 20260902171232.png
    • You can also return an HTTP response with whatever error code you would like as well, this is done using the HttpResponse() function, where you first input the status, and then the message that is associated with it
  • Django Template:
    • Django Template basically is used to specify the HOW of how your data will be presented inside of an application
    • It combines the use of HTML elements with something like python code in order to dynamically fill in and render the page with whatever data you might have gotten from your model
    • Pasted image 20260902171646.png
    • A django template is basically an html file with django template tags and variables which are then interpreted by the django template engine to create your dynamic HTML code and ship it out for rendering
    • In order to add in a new template inside of your course structure, you would do so by just adding in a templates/ directory under your application directory
    • You then create a second directory of projectname/ and then inside of that folder you have all of the .html files that would be used in order to render content dynamically
    • The main reason for the second project name directory is to distinguish those template files directly from other applications that might have template files with the exact same names, letting you know where you are pretty much working at
    • Pasted image 20260902171942.png
    • Your template is rendered with something called a context which basically is a dictionary like object that is returned by your views
    • Rendering would then actually replace your variables and tags with real values, which are looked up in the context of your execute tags, allowing them to be filled in with whatever data you would like
    • The above is basically an example of an if/else tag which is defined using that whole {%%} stuff, and it would basically check, hey, if this course_list variable is true, then render this unordered list with {%for course in course_list%} for loop, to populate it
    • if it is not though, then simply render the paragraph text saying that no courses were found
    • This allows for really good dynamic programming with reusable code for each of your applications
    • Pasted image 20260902172421.png
    • Pasted image 20260902172518.png
    • After having created the actual template you wanted with your HTML file, then you can actual render it inside of your view and what not using the render() function and specifying everything that needs to go in there like the needed context and request and such
    • This lets the actual template be used to dictate how the data this person requested gets rendered
    • If you want to decorate your pages, you can do so very easily by just adding in CSS using the {% load static%} command which you can then just use a <link></link> html tag with the reference to your CSS style, which then would get applied to your HTML code normally, making it all nice and pretty for you

==Summary

  • The Model-View-Controller design pattern divides application logic into three components:
  • Model accesses and manipulates data
  • View presents data in various forms
  • Controller coordinates between Model and View
  • The Django Model-View-Template pattern is like MVC, except there is no Controller, and the Django server performs the controller function.
  • In Django, a View is a Python function that takes a Web request and applies the necessary logic to generate a Web response.
  • Django uses a template containing static HTML elements and special Python code to generate dynamic Web pages.
  • When you create a Django project, Django creates some core files.
  • manage.py is a command-line interface used to interact with the Django project
  • settings.py contains the settings and configurations for your Django project
  • urls.py contains the URL and routing definitions of your Django app
  • You start building a Django admin site by creating an admin user.
  • You can then log in as a superuser and register your models to the admin site so you can manage them.
  • You can customize the admin form and add search and filters.
  • A Django View takes a Web request such as HTTP GET, POST, DELETE, or UPDATE and returns a Web response. The web response can be a string, JSON/XML file, HTML page, or an error status indicating client or server-side errors.
  • You create templates in Django to specify how your data will be presented. A Django template combines static HTML elements with Django template tags and variables to describe how the dynamic parts will be inserted. These work together to generate an HTML page rendered in a user’s web browser.

==Cheat Sheet

Package/MethodDescriptionCode Example
count()Counts the number of objects.MyModel.objects.count()
Sum()Provides the sum of a field.MyModel.objects.aggregate(Sum(‘field’))
Avg()Calculates the average of a field.MyModel.objects.aggregate(Avg(‘field’))
Max()Provides the maximum value of a field.MyModel.objects.aggregate(Max(‘field’))
Min()Provides the minimum value of a field.MyModel.objects.aggregate(Min(‘field’))
order_by()Orders objects based on a field.MyModel.objects.order_by(‘field’)
order_by(-)Order objects based on fields in descending order.MyModel.objects.order_by(‘-field’)
select_relatedPerforms inner join.MyModel.objects.select_related(‘related_model’)
prefetch_relatedPerforms left Outer join.MyModel.objects.prefetch_related(‘related_model’)
many_to_manyPerforms many-to-many join.obj.many_to_many_field.all()
filter(ForeignKey)Performs conditional joins.MyModel.objects.filter(related_model__isnull=True)

References