Django

Django is a Python framework that makes it easier to create web sites using Python.
Django takes care of the difficult stuff so that you can concentrate on building your web applications.
Django emphasizes reusability of components, also referred to as DRY (Don't Repeat Yourself), and comes with ready-to-use features like login system, database connection and CRUD operations (Create Read Update Delete).

Django
Django is especially helpful for database driven websites.

How does Django Work?
Django follows the MVT design pattern (Model View Template).

Model - The data you want to present, usually data from a database.
View - A request handler that returns the relevant template and content - based on the request from the user.
Template - A text file (like an HTML file) containing the layout of the web page, with logic on how to display the data.

Model
The model provides data from the database.
In Django, the data is delivered as an Object Relational Mapping (ORM), which is a technique designed to make it easier to work with databases.

The most common way to extract data from a database is SQL. One problem with SQL is that you have to have a pretty good understanding of the database structure to be able to work with it.

Django, with ORM, makes it easier to communicate with the database, without having to write complex SQL statements.

The models are usually located in a file called models.py.


View
A view is a function or method that takes http requests as arguments, imports the relevant model(s), and finds out what data to send to the template, and returns the final result. The views are usually located in a file called views.py.


Template
A template is a file where you describe how the result should be represented.
Templates are often .html files, with HTML code describing the layout of a web page, but it can also be in other file formats to present other results, but we will concentrate on .html files.


URLs
Django also provides a way to navigate around the different pages in a website.

When a user requests a URL, Django decides which view it will send it to. This is done in a file called urls.py.
  1. Create Virtual Environment
    Create Virtual Environment
    Virtual Environment
    It is suggested to have a dedicated virtual environment for each Django project, and one way to manage a virtual environment is venv, which is included in Python.

    The name of the virtual environment is your choice, in this tutorial we will call it myworld.

    Type the following in the command prompt, remember to navigate to where you want to create your project
                         
                            py -m venv env
                            
    

    activate the environment

         
            env\Scripts\activate
            
    
  2. Installation of Django
             
                py -m pip install Django
                
    
  3. Check Django Version
             
                django-admin --version
                
    
  4. Create Requirements (Create a requirements.txt)
             
                py -m pip freeze > requirements.txt
                
    
  5. install requirements.txt
             
                pip install -r requirements.txt
                
    
  6. Create django project
             
                django-admin startproject my_project
                
    
  7. Go in the project
             
                cd my_project
                
    
  8. Run the Django Project
             
                python manage.py runserver
                
    
  9. Create Migrate
             
                py manage.py makemigrations
                
    
  10. Migrate changes
             
                py manage.py migrate
                
    
  11. open a Python shell
             
                py manage.py shell
                
    
  12. Django Create App
    Django Create App
    What is an App? An app is a web application that has a specific meaning in your project, like a home page, a contact form, or a members database. In this tutorial we will create an app that allows us to list and register members in a database. But first, let's just create a simple Django app that displays "Hello World!".
                                                         
                                        python manage.py startapp app_name
                                          
                              
  13. Django Views
    Django Views
    Views
    Django views are Python functions that takes http requests and returns http response, like HTML documents.

    A web page that uses Django is full of views with different tasks and missions.

    Views are usually put in a file called views.py located on your app's folder.

    There is a views.py in your app folder

    views.py

                                                         
                                        from django.shortcuts import render
                                        from django.http import HttpResponse
                                        
                                        def members(request):
                                            return HttpResponse("Hello world!")
                                          
                              
  14. Django URLs
    Django URLs
    URLs
    Create a file named urls.py in the same folder as the views.py file, and type this code in it
        
            from django.contrib import admin
            from django.urls import include, path
            
            urlpatterns = [
                path('', include('members.urls')),
                path('admin/', admin.site.urls),
            ]
    
    
  15. View SQL
    View SQL
    As a side-note: you can view the SQL statement that were executed from the migration above. All you have to do is to run this command, with the migration number
        
            py manage.py sqlmigrate app_name migrate_number
    
    
  16. Django Models
    Django Models
    A Django model is a table in your database.

    Django Models
    Up until now in this tutorial, output has been static data from Python or HTML templates.

    Now we will see how Django allows us to work with data, without having to change or upload files in the prosess.

    In Django, data is created in objects, called Models, and is actually tables in a database.


    Create Table (Model)
    To create a model, navigate to the models.py file in the /members/ folder.

    Open it, and add a Member table by creating a Member class, and describe the table fields in it
    
        from django.db import modelsclass Member(models.Model):
      firstname = models.CharField(max_length=255)
      lastname = models.CharField(max_length=255)
    
    
  17. Django Insert Data
    Django Insert Data
    Add Records The Members table created in the previous chapter is empty. We will use the Python interpreter (Python shell) to add some members to it.

                                    
                                        py manage.py shell
                                
                                

                                    
                                        from members.models import Member
                                
                                

                                    
                                        Member.objects.all()
                                
                                

    Output:<QuerySet []>
    A QuerySet is a collection of data from a database.

                                    
                                        member = Member(firstname='Emil', lastname='Refsnes')
                                
                                
                                    
                                        member.save()
                                
                                

                                    
                                        Member.objects.all().values()
                                
                                

                                    
    member1 = Member(firstname='Tobias', lastname='Refsnes')
     member2 = Member(firstname='Linus', lastname='Refsnes')
    member3 = Member(firstname='Lene', lastname='Refsnes')
     member4 = Member(firstname='Stale', lastname='Refsnes')
     member5 = Member(firstname='Jane', lastname='Doe')
     members_list = [member1, member2, member3, member4, member5]
    for x in members_list:
        x.save()
                                
                                
  18. Django Update Data
    Django Update Data
    Update Records
    To update records that are already in the database, we first have to get the record we want to update

                                    
                                        from members.models import Member
                                
                                
                                    
                                        x = Member.objects.all()[4]
                                
                                

    x will now represent the member at index 4

                                    
                                        x.firstname = "Stalikken"
                                
                                
                                    
                                        x.save()
                                
                                
  19. Django Delete Data
    Django Delete Data
    Delete Records
    To delete a record in a table, start by getting the record you want to delete

                                    
                                        from members.models import Member
                                
                                
                                    
                                        x = Member.objects.all()[4]
                                
                                

    x will now represent the member at index 4

                                    
                                        x.delete()
                                
                                
  20. Django Update Model
    Django Update Model
    Add Fields in the Model
    To add a field to a table after it is created, open the models.py file, and make your changes

                    
                        from django.db import modelsclass Member(models.Model):
      firstname = models.CharField(max_length=255)
      lastname = models.CharField(max_length=255)
      phone = models.IntegerField(null=True)
      joined_date = models.DateField(null=True)
                
                

                    
                        py manage.py shell
    
                
                    
                        from members.models import Member
    x = Member.objects.all()[0]
    x.phone = 5551234
    x.joined_date = '2022-01-05'
    x.save()
    
                
  21. Django Prepare Template
    Django Prepare Template
    Create Template
    After creating Models, with the fields and data we want in them, it is time to display the data in a web page.


    Start by creating an HTML file named all_members.html and place it in the /templates/ folder

                
                    {% for x in mymembers %}
                    
  22. {{ x.firstname }} {{ x.lastname }}
  23. {% endfor %}

                
                 
    
            
  24. Add Master Template
    Add Master Template
    The extends Tag
    In the previous pages we created two templates, one for listing all members, and one for details about a member.

    The templates have a set of HTML code that are the same for both templates.

    Django provides a way of making a "parent template" that you can include in all pages to for the stuff that are the same in all pages.

    Start by creating a template called master.html, with all the necessary HTML elements

                                            
                                                <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <head>
            <title>{% block title %}{% endblock %}</title>
            {% block css %}{% endblock %}
          </head>
          <body>
          
          {% block content %}{% endblock %}
          
        
          {% block js %}{% endblock %}
    </body>
    </html>
                                        
                                        
  25. Django 404 (page not found)
    Django 404 (page not found)
    Page Not Found
    If you try to access a page that does not exist (a 404 error), Django directs you to a built-in view that handles 404 errors.


    If you got the first result, you got directed to the built-in Django 404 template.


    If you got the second result, then DEBUG is set to True in your settings, and you must set it to False to get directed to the 404 template.


    This is done in the settings.py file, which is located in the project folder, in our case the my_tennis_club folder, where you also have to specify the host name from where your project runs from

    Important: When DEBUG = False, Django requires you to specify the hosts you will allow this Django project to run from.

    In production, this should be replaced with a proper domain name:

    ALLOWED_HOSTS = ['yourdomain.com']

    Customize the 404 Template
    Django will look for a file named 404.html in the templates folder, and display it when there is a 404 error.

    If no such file exists, Django shows the "Not Found" that you saw in the example above.

    To customize this message, all you have to do is to create a file in the templates folder and name it 404.html, and fill it with write whatever you want

                                            
                                                
                                        
                                        

                                        
                                           
                                    
                                    
  26. Add Test View
    Add Test View
    Test View
    When testing different aspects of Django, it can be a good idea to have somewhere to test code without destroying the main project.

    This is optional off course, but if you like to follow all steps in this tutorial, you should add a test view that is excactly like the one we create below. Then you can follow the examples and try them out on your own computer.


    Add View
    Start by adding a view called "testing" in the views.py file
  27. Django Admin
    Django Admin
    Django Admin
    Django Admin is a really great tool in Django, it is actually a CRUD* user interface of all your models!


    *CRUD stands for Create Read Update Delete.
  28. Admin - Create User
    Admin - Create User
    Create User
    To be able to log into the admin application, we need to create a user.

    This is done by typing this command in the command view
    
        py manage.py createsuperuser
    
    
  29. Admin - Include Member
    Admin - Include Member
    Include Member in the Admin Interface
    To include the Member model in the admin interface, we have to tell Django that this model should be visible in the admin interface.


    This is done in a file called admin.py, and is located in your app's folder, which in our case is the members folder.

                                      
                                        from django.contrib import admin
                              
                          

                                    
                                        admin.site.register(Member)
                            
                        
  30. Admin - Set Fields to Display
    Admin - Set Fields to Display
    Make the List Display More Reader-Friendly

    When you display a Model as a list, Django displays each record as the string representation of the record object, which in our case is "Member object (1)", "Member object(2)" etc.


    We can control the fields to display by specifying them in in a list_display property in the admin.py file.

    First create a MemberAdmin() class and specify the list_display tuple, like this

    models.py

                                        
                                            def __str__(self):
        return f"{self.firstname} {self.lastname}"
                                        
                                        

    admin.py

                                        
                                            class MemberAdmin(admin.ModelAdmin):
      list_display = ("firstname", "lastname", "joined_date",)
      
    admin.site.register(Member, MemberAdmin)
                                        
                                        
  31. Django Template Variables
    Django Template Variables
    Template Variables
    In Django templates, you can render variables by putting them inside {{ }} brackets

                                        
                                            <h1>Hello {{ firstname }}, how are you?</h1>
                                        
                                        

                                        
                                            context = {
                                                'firstname': 'Linus',
                                              }
                                        
                                        

    You can also create variables directly in the template, by using the {% with %} template tag

                                        
                                            {% with firstname="Tobias" %}
                                            <h1>Hello {{ firstname }}, how are you?</h1>
                                            
                                        

                                        
                                            from .models import Member
                                            
                                        
                                            
                                                mymembers = Member.objects.all().values()
      context = {
        'mymembers': mymembers,
      }
                                                
                                            

    We use the Django template tag {% for %} to loop through the members.

                                                
                                                    {% for x in mymembers %}
        <li>{{ x.firstname }}</li>
      {% endfor %}
                                                    
                                                
  32. Django Template Tags
    Django Template Tags
    Template Tags
    In Django templates, you can perform programming logic like executing if statements and for loops.


    These keywords, if and for, are called "template tags" in Django.

    To execute template tags, we surround them in {% %} brackets.


    Django Code
    The template tags are a way of telling Django that here comes something else than plain HTML.

    The template tags allows us to to do some programming on the server before sending HTML to the client. Tag Reference
    Tag Description
    autoescape Specifies if autoescape mode is on or off
    block Specifies a block section
    comment Specifies a comment section
    csrf_token Protects forms from Cross Site Request Forgeries
    cycle Specifies content to use in each cycle of a loop
    debug Specifies debugging information
    extends Specifies a parent template
    filter Filters content before returning it
    firstof Returns the first not empty variable
    for Specifies a for loop
    if Specifies a if statement
    ifchanged Used in for loops. Outputs a block only if a value has changed since the last iteration
    include Specifies included content/template
    load Loads template tags from another library
    lorem Outputs random text
    now Outputs the current date/time
    regroup Sorts an object by a group
    resetcycle Used in cycles. Resets the cycle
    spaceless Removes whitespace between HTML tags
    templatetag Outputs a specified template tag
    url Returns the absolute URL part of a URL
    verbatim Specifies contents that should not be rendered by the template engine
    widthratio Calculates a width value based on the ratio between a given value and a max value
    with Specifies a variable to use in the block
  33. Django if Tag
    Django if Tag
    If Statement An if statement evaluates a variable and executes a block of code if the value is true. Elif The elif keyword says "if the previous conditions were not true, then try this condition". Else The else keyword catches anything which isn't caught by the preceding conditions.

                                        
                                            {% if greeting == 1 %}
                                            
                                          {% endif %} 
                                        
                                        

                                        
                                            {% if greeting == 1 %}
                                           
                                          {% elif greeting == 2 %}
                                            
                                          {% endif %} 
                                        
                                        

                                        
                                            {% if greeting == 1 %}
                                           
                                          {% elif greeting == 2 %}
                                            
                                          {% else %}
                                           
                                          {% endif %} 
                                            
                                        
  34. Operators

                                        
                                            {% if greeting == 2 %}
                                            
                                          {% endif %}
                                            
                                        

                                        
                                            {% if greeting == 2 %}
                                            
                                          {% endif %}
                                            
                                        

                                        
                                            {% if greeting ! = 2 %}
                                            
                                          {% endif %}
                                            
                                        

    > Is less than.
    <= Is less than, or equal to.
    >= Is greater than, or equal to.

                                        
                                            {% if greeting < 2 %}
                                            
                                          {% endif %}
                                            
                                        

    To check if more than one condition is true.

                                        
                                            {% if greeting == 1 and day == "Friday" %}
                                            
                                          {% endif %}
                                            
                                        

                                        
                                            {% if greeting == 2 %}
                                            
                                          {% endif %}
                                            
                                        

    To check if one of the conditions is true.

                                        
                                            {% if greeting == 1 or greeting == 5 %}
                                            
                                          {% endif %}
                                            
                                        

    To check if a certain item is present in an object.

                                        
                                            {% if 'Banana' in fruits %}
                                            
                                          {% endif %}
                                            
                                        

    To check if a certain item is not present in an object.

                                        
                                            {% if 'Banana' not in fruits %}
                                            
                                          {% endif %}
                                            
                                        

    Check if two objects are the same. This operator is different from the == operator, because the == operator checks the values of two objects, but the is operator checks the identity of two objects.

                                        
                                            {% if x is y %}
      
    {% else %}
      
    {% endif %}
                                            
                                        
  35. Django for Tag
    Django for Tag
    For Loops
    A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.


    Reversed
    The reversed keyword is used when you want to do the loop in reversed order.


    Empty
    The empty keyword can be used if you want to do something special if the object is empty.

                                        
                                            {% for x in fruits %}{% endfor %}
                                        
                                        

                                        
                                            {% for x in members reversed %}
      
    {% endfor %} 
                                        
                                        

                                        
                                            {% for x in emptytestobject %}
       
      {% empty %}  {% endfor %}
                                            
                                        
  36. Loop Variables
    Loop Variables
    Django has some variables that are available for you inside a loop:


    forloop.counter

    forloop.counter0

    forloop.first

    forloop.last

    forloop.parentloop

    forloop.revcounter

    forloop.revcounter0

    The current iteration, starting at 1.

                                        
                                            {% for x in fruits %}   {{ forloop.counter }}  {% endfor %}
                                        
                                        

    The current iteration, starting at 0.

                                        
                                            {% for x in fruits %}                                        {{ forloop.counter0 }}                                      {% endfor %}
                                        
                                        

    Allows you to test if the loop is on its first iteration.

                                        
                                            {% for x in fruits %}
        <li
          {% if forloop.first %}
            style='background-color:lightblue;'
          {% endif %}
        >{{ x }}</li>
      {% endfor %}
                                            
                                        

    Allows you to test if the loop is on its last iteration.

                                        
                                            {% for x in fruits %}
        <li
          {% if forloop.last %}
            style='background-color:lightblue;'
          {% endif %}
        >{{ x }}</li>
      {% endfor %}
                                            
                                        

    The current iteration if you start at the end and count backwards, ending up at 1.

                                        
                                            {% for x in fruits %}
    {{ forloop.revcounter }}
                                          {% endfor %}
                                            
                                        

    The current iteration if you start at the end and count backwards, ending up at 0.

                                        
                                            {% for x in fruits %}
       {{ forloop.revcounter0 }}
      {% endfor %}        
                                        
  37. Django comment Tag
    Django comment Tag
    Comments
    Comments allows you to have sections of code that should be ignored.


    Comment Description
    You can add a message to your comment, to help you remember why you wrote the comment, or as message to other people reading the code.
                                        
                                            {% comment %}
      
    {% endcomment %}
                                        
                                        

                                            
                                                {% comment "this was the original welcome message" %}
      
    {% endcomment %}
                                            
                                            

                                                
                             <h1>Welcome{# Everyone#}</h1>
                                                
                                                
  38. Django include Tag
    Django include Tag
    Include
    The include tag allows you to include a template inside the current template.

    This is useful when you have a block of content that is the same for many pages.


    Variables in Include
    You can send variables into the template by using the with keyword.

    In the include file, you refer to the variables by using the {{ variablename }} syntax
                                        
                                            {% include 'footer.html' %} 
                                        
                                        

    Variables in Include

                                            
    {% include "mymenu.html" with me="TOBIAS" sponsor="W3SCHOOLS" %}
                                            
                                            

    mymenu.html

                                                
                                                    <div>HOME | {{ me }} | ABOUT | FORUM | {{ sponsor }}</div>
                                                
                                                
  39. Django QuerySet
    Django QuerySet
    Django QuerySet
    A QuerySet is a collection of data from a database.

    A QuerySet is built up as a list of objects.

    QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data at an early stage.
  40. QuerySet - Get Data
    QuerySet - Get Data
    Get Data There are different methods to get data from a model into a QuerySet. The values() Method The values() method allows you to return each object as a Python dictionary, with the names and values as key/value pairs Return Specific Columns The values_list() method allows you to return only the columns that you specify.
  41. Django QuerySet - Filter
    Django QuerySet - Filter
    QuerySet Filter
    The filter() method is used to filter your search, and allows you to return only the rows that matches the search term.


    AND
    The filter() method takes the arguments as **kwargs (keyword arguments), so you can filter on more than one field by sepearting them by a comma.


    OR
    To return records where firstname is Emil or firstname is Tobias (meaning: returning records that matches either query, not necessarily both) is not as easy as the AND example above.

    We can use multiple filter() methods, separated by a pipe | character. The results will merge into one model.


    Field Lookups
    Django has its own way of specifying SQL statements and WHERE clauses.
    To make specific where clasuses in Django, use "Field lookups".
    Field lookups are keywords that represents specific SQL keywords.

    In SQL, the above statement would be written like this:
    SELECT * FROM members WHERE firstname = 'Emil';

                                        
    mydata = Member.objects.filter(firstname='Emil').values()
                                        
                                        

    In SQL, the above statement would be written like this:
    SELECT * FROM members WHERE lastname = 'Refsnes' AND id = 2;

                                        
     mydata = Member.objects.filter(lastname='Refsnes', id=2).values()
                                        
                                        

    In SQL, the above statement would be written like this:
    SELECT * FROM members WHERE firstname = 'Emil' OR firstname = 'Tobias';

                                        
    mydata = Member.objects.filter(firstname='Emil').values() | Member.objects.filter(firstname='Tobias').values()
                                            
                                        
                                            
     from django.db.models import Qmydata = Member.objects.filter(Q(firstname='Emil') | Q(firstname='Tobias')).values()
                                                
                                            

    Is the same as the SQL statment:
    WHERE firstname LIKE 'L%'

                                                                               .filter(firstname__startswith='L');
                                        
                                        
  42. Field Lookups Reference
    Field Lookups Reference
    Keyword Description
    contains Contains the phrase
    icontains Same as contains, but case-insensitive
    date Matches a date
    day Matches a date (day of month, 1-31) (for dates)
    endswith Ends with
    iendswith Same as endswidth, but case-insensitive
    exact An exact match
    iexact Same as exact, but case-insensitive
    in Matches one of the values
    isnull Matches NULL values
    gt Greater than
    gte Greater than, or equal to
    hour Matches an hour (for datetimes)
    lt Less than
    lte Less than, or equal to
    minute Matches a minute (for datetimes)
    month Matches a month (for dates)
    quarter Matches a quarter of the year (1-4) (for dates)
    range Match between
    regex Matches a regular expression
    iregex Same as regex, but case-insensitive
    second Matches a second (for datetimes)
    startswith Starts with
    istartswith Same as startswith, but case-insensitive
    time Matches a time (for datetimes)
    week Matches a week number (1-53) (for dates)
    week_day Matches a day of week (1-7) 1 is sunday
    iso_week_day Matches a ISO 8601 day of week (1-7) 1 is monday
    year Matches a year (for dates)
    iso_year Matches an ISO 8601 year (for dates)
  43. QuerySet - Order By
    QuerySet - Order By
    Order By
    To sort QuerySets, Django uses the order_by() method


    Descending Order
    By default, the result is sorted ascending (the lowest value first), to change the direction to descending (the highest value first), use the minus sign (NOT), - in front of the field name


    Multiple Order Bys
    To order by more than one field, separate the fieldnames with a comma in the order_by() method

    In SQL, the above statement would be written like this:
    SELECT * FROM members ORDER BY firstname;

                                        
    mydata = Member.objects.all().order_by('firstname').values()
                                        
                                        

    In SQL, the above statement would be written like this:
    SELECT * FROM members ORDER BY firstname DESC;

                                        
                                            mydata = Member.objects.all().order_by('-firstname').values()
                                        
                                        

    In SQL, the above statement would be written like this:
    SELECT * FROM members ORDER BY lastname ASC, id DESC;

                                        
    mydata = Member.objects.all().order_by('lastname', '-id').values()
                                            
                                        
  44. Django QuerySet - Filter
    Django QuerySet - Filter
    Create Static Folder
    When building web applications, you probably want to add some static files like images or css files.


    Start by creating a folder named static in your project, the same place where you created the templates folder:

    The name of the folder has to be static.

    Add a CSS file in the static folder, the name is your choice, we will call it myfirst.css


    Didn't Work?
    Just testing? If you just want to play around, and not going to deploy your work, you can set DEBUG = True in the settings.py file, and the example above will work.

    Plan to deploy? If you plan to deploy your work, you should set DEBUG = False in the settings.py file. The example above will fail, because Django has no built-in solution for serving static files, but there are other ways to serve static files

                                        
                                            {% load static %}
                                        
                                        

                                        
     <link rel="stylesheet" href="{% static 'myfirst.css' %}">
                                        
                                        
  45. Django Installing WhiteNoise
    Django Installing WhiteNoise
    WhiteNoise
    Django does not have a built-in solution for serving static files, at least not in production when DEBUG has to be False.

    We have to use a third-party solution to accomplish this.

    In this Tutorial we will use WhiteNoise, which is a Python library, built for serving static files.


    Modify Settings
    To make Django aware of you wanting to run WhitNoise, you have to specify it in the MIDDLEWARE list in settings.py file


    Handle Static Files
    Static files in your project, like stylesheets, JavaScripts, and images, are not handled automatically by Django when DEBUG = False.

    When DEBUG = True, this worked fine, all we had to do was to put them in the static folder of the application.

    When DEBUG = False, static files have to be collected and put in a specified folder before we can use it.


    Collect Static Files
    To collect all necessary static files for your project, start by specifying a STATIC_ROOT property in the settings.py file.

    This specifies a folder where you want to collect your static files.

    You can call the folder whatever you like, we will call it productionfiles


                                        
                                            pip install whitenoise
                                        
                                        

                                        
    MIDDLEWARE = [
                            'whitenoise.middleware.WhiteNoiseMiddleware',
                                        ]
    STATIC_ROOT = BASE_DIR / 'productionfiles'STATIC_URL = 'static/'
                                        
                                        

                                        
                                            py manage.py collectstatic
                                        
                                        
  46. Django - Global Static Files
    Django - Global Static Files
    Add a Global File
    We have learned how to add a static file in the application's static folder, and how to use it in the application.

    But what if other applications in your project wants to use the file?

    Then we have to create a folder on the root directory and put the file(s) there.

    It is not enough to create a static folder in the root directory, and Django will fix the rest. We have to tell Django where to look for these static files.

    Add a CSS file in the mystaticfiles folder, the name is your choice, we will call it myglobal.css

    In the STATICFILES_DIRS list, you can list all the directories where Django should look for static files.

    The BASE_DIR keyword represents the root directory of the project, and together with the / "mystaticfiles", it means the mystaticfiles folder in the root directory.

    Search Order
    If you have files with the same name, Django will use the first occurrence of the file.

    The search starts in the directories listed in STATICFILES_DIRS, using the order you have provided. Then, if the file is not found, the search continues in the static folder of each application.

    Modify the Template
    Now you have a global CSS file for the entire project, which can be accessed from all your applications.

    To use it in a template, use the same syntax as you did for the myfirst.css file:

                                        
                                            #Add this in your settings.py file:
    STATICFILES_DIRS = [
        BASE_DIR / 'mystaticfiles'
    ]
                                        
                                        

                                        
                                            {% load static %}
                                        
                                        

                                        
        <link rel="stylesheet" href="{% static 'myglobal.css' %}">
                                        
                                        

                                        
                                            py manage.py collectstatic
                                        
                                        
  47. Django with PostgreSQL
    Django with PostgreSQL
    PostgreSQL database is an open source relational database, which should cover most demands you have when creating a database for a Django project.

    It has a good reputation, it is reliable, and it perform well under most circumstances.

    We will add a PostgreSQL database to our Django project.

    To be able to use PostgreSQL in Django we have to install a package called psycopg2.

    The psycopg2 package is a driver that is necessary for PostgreSQL to work in Python.

    We also need a server where we can host the database.

                                        
                                            pip install psycopg2-binary
                                        
                                        

                                        
                                            DATABASES = {
                                                'default': {
                                                    'ENGINE': 'django.db.backends.postgresql',
                                                    'NAME': 'postgres',
                                                    'USER': 'masteruser',
                                                    'PASSWORD': '12345678',
                                                    'HOST': 'w3-django-project.cdxmgq9zqqlr.us-east-1.rds.amazonaws.com',
                                                    'PORT': '5432'
                                                }
                                            }
                                            .
                                            
                                        
                                        
  48. Deploy Django - django.config
    Deploy Django - django.config
    Provider-Specific Settings We have chosen AWS as our hosting provider, and Elastic Beanstalk as a service to deploy the Django project, and it has some specific requirements. .ebextension Folder It requires that you create a folder on the root level of your project called .ebextensions Create django.config File In the .ebextensions folder, create a file called django.config

                                        
                                            mkdir .ebextensions
                                        
                                        

                                        
                                            option_settings:
      aws:elasticbeanstalk:container:python:
        WSGIPath: my_tennis_club.wsgi:application
                                        
                                        
  49. Django Template Tags Reference
    Django Template Tags Reference
    Tag Description
    autoescape Specifies if autoescape mode is on or off
    block Specifies a block section
    comment Specifies a comment section
    csrf_token Protects forms from Cross Site Request Forgeries
    cycle Specifies content to use in each cycle of a loop
    debug Specifies debugging information
    extends Specifies a parent template
    filter Filters content before returning it
    firstof Returns the first not empty variable
    for Specifies a for loop
    if Specifies a if statement
    ifchanged Used in for loops. Outputs a block only if a value has changed since the last iteration
    include Specifies included content/template
    load Loads template tags from another library
    lorem Outputs random text
    now Outputs the current date/time
    regroup Sorts an object by a group
    resetcycle Used in cycles. Resets the cycle
    spaceless Removes whitespace between HTML tags
    templatetag Outputs a specified template tag
    url Returns the absolute URL part of a URL
    verbatim Specifies contents that should not be rendered by the template engine
    widthratio Calculates a width value based on the ratio between a given value and a max value
    with Specifies a variable to use in the block
  50. Filter Reference
    Filter Reference
    Keyword Description
    add Adds a specified value.
    addslashes Adds a slash before any quote characters, to escape strings.
    capfirst Returns the first letter in uppercase.
    center Centers the value in the middle of a specified width.
    cut Removes any specified character or phrases.
    date Returns dates in the specified format.
    default Returns a specified value if the value is False.
    default_if_none Returns a specified value if the value is None.
    dictsort Sorts a dictionary by the given value.
    dictsortreversed Sorts a dictionary reversed, by the given value.
    divisibleby Returns True if the value can be divided by the specified number, otherwise it returns False.
    escape Escapes HTML code from a string.
    escapejs Escapes JavaScript code from a string.
    filesizeformat Returns a number into a file size format.
    first Returns the first item of an object (for Strings, the first character is returned).
    floatformat Rounds floating numbers to a specified number of decimals, default one decimal.
    force_escape Escapes HTML code from a string.
    get_digit Returns a specific digit of a number.
    iriencode Convert an IRI into a URL friendly string.
    join Returns the items of a list into a string.
    json_script Returns an object into a JSON object surrounded by <script></script> tags.
    last Returns the last item of an object (for Strings, the last character is returned).
    length Returns the number of items in an object, or the number of characters in a string.
    length_is Returns True if the length is the same as the specified number
    linebreaks Returns the text with <br> instead of line breaks, and <p> instead of more than one line break.
    linebreaksbr Returns the text with <br> instead of line breaks.
    linenumbers Returns the text with line numbers for each line.
    ljust Left aligns the value according to a specified width
    lower Returns the text in lower case letters.
    make_list Converts a value into a list object.
    phone2numeric Converts phone numbers with letters into numeric phone numbers.
    pluralize Adds a 's' at the end of a value if the specified numeric value is not 1.
    pprint  
    random Returns a random item of an object
    rjust Right aligns the value according to a specified width
    safe Marks that this text is safe and should not be HTML escaped.
    safeseq Marks each item of an object as safe and the item should not be HTML escaped.
    slice Returns a specified slice of a text or object.
    slugify Converts text into one long alphanumeric-lower-case word.
    stringformat Converts the value into a specified format.
    striptags Removes HTML tags from a text.
    time Returns a time in the specified format.
    timesince Returns the difference between two datetimes.
    timeuntil Returns the difference between two datetimes.
    title Upper cases the first character of each word in a text, all other characters are converted to lower case.
    truncatechars Shortens a string into the specified number of characters.
    truncatechars_html Shortens a string into the specified number of characters, not considering the length of any HTML tags.
    truncatewords Shortens a string into the specified number of words.
    truncatewords_html Shortens a string into the specified number of words, not considering any HTML tags.
    unordered_list Returns the items of an object as an unordered HTML list.
    upper Returns the text in upper case letters.
    urlencode URL encodes a string.
    urlize Returns any URLs in a string as HTML links.
    urlizetrunc Returns any URLs in a string as HTML links, but shortens the links into the specified number of characters.
    wordcount Returns the number of words in a text.
    wordwrap Wrap words at a specified number of characters.
    yesno Converts Booleans values into specified values.
    i18n  
    l10n  
    tz  
  51. QuerySet Field Lookups Reference
    QuerySet Field Lookups Reference
    Keyword Description
    contains Contains the phrase
    icontains Same as contains, but case-insensitive
    date Matches a date
    day Matches a date (day of month, 1-31) (for dates)
    endswith Ends with
    iendswith Same as endswidth, but case-insensitive
    exact An exact match
    iexact Same as exact, but case-insensitive
    in Matches one of the values
    isnull Matches NULL values
    gt Greater than
    gte Greater than, or equal to
    hour Matches an hour (for datetimes)
    lt Less than
    lte Less than, or equal to
    minute Matches a minute (for datetimes)
    month Matches a month (for dates)
    quarter Matches a quarter of the year (1-4) (for dates)
    range Match between
    regex Matches a regular expression
    iregex Same as regex, but case-insensitive
    second Matches a second (for datetimes)
    startswith Starts with
    istartswith Same as startswith, but case-insensitive
    time Matches a time (for datetimes)
    week Matches a week number (1-53) (for dates)
    week_day Matches a day of week (1-7) 1 is sunday
    iso_week_day Matches a ISO 8601 day of week (1-7) 1 is monday
    year Matches a year (for dates)
    iso_year Matches an ISO 8601 year (for dates)